加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何处理MVC5中的配置和代码中的404错误?

发布时间:2020-12-16 00:00:17 所属栏目:asp.Net 来源:网络整理
导读:我已经实现了以下链接中提到的异常处理 How to pass error message to error view in MVC 5? 它工作正常.但我要求处理404错误. 我怎样才能做到这一点? 如果我使用下面的代码, customErrors mode="On" error statusCode="404" redirect="/Home/Error"/error/
我已经实现了以下链接中提到的异常处理

How to pass error message to error view in MVC 5?

它工作正常.但我要求处理404错误.

我怎样才能做到这一点?

如果我使用下面的代码,

<customErrors mode="On">
  <error statusCode="404" redirect="/Home/Error"></error>
</customErrors>

当发生任何404错误时,它可以正常工作.但是如果发生任何其他异常,那么我的error.cshtml调用两次并显示相同的异常两次.

解决方法

web.config中

关闭system.web中的自定义错误

<system.web>
    <customErrors mode="Off" />
</system.web>

在system.webServer中配置http错误

<system.webServer>
    <httpErrors errorMode="Custom" existingResponse="Auto">
      <clear />
      <error statusCode="404" responseMode="ExecuteURL" path="/NotFound" />
      <error statusCode="500" responseMode="ExecuteURL" path="/Error" />
    </httpErrors>
</system.webServer>

创建简单的错误控制器来处理这些请求ErrorContoller.cs

[AllowAnonymous]
public class ErrorController : Controller {
    // GET: Error
    public ActionResult NotFound() {
        var statusCode = (int)System.Net.HttpStatusCode.NotFound;
        Response.StatusCode = statusCode;
        Response.TrySkipIisCustomErrors = true;
        HttpContext.Response.StatusCode = statusCode;
        HttpContext.Response.TrySkipIisCustomErrors = true;
        return View();
    }

    public ActionResult Error() {
        Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
        Response.TrySkipIisCustomErrors = true;
        return View();
    }
}

配置路由RouteConfig.cs

public static void RegisterRoutes(RouteCollection routes) {

    //...other routes 

    routes.MapRoute(
        name: "404-NotFound",url: "NotFound",defaults: new { controller = "Error",action = "NotFound" }
    );

    routes.MapRoute(
        name: "500-Error",url: "Error",action = "Error" }
    );

    //..other routes

    //I also put a catch all mapping as last route

    //Catch All InValid (NotFound) Routes
    routes.MapRoute(
        name: "NotFound",url: "{*url}",action = "NotFound" }
    );
}

最后确保您拥有控制器操作的视图

Views/Shared/NotFound.cshtml
Views/Shared/Error.cshtml

如果您要处理任何其他错误,可以按照该模式并根据需要添加.这将避免重定向并保持引发的原始http错误状态.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读