如何处理MVC5中的配置和代码中的404错误?

时间:2022-11-29 13:53:39

I have implemented exception handling as mentioned in below link

我已经实现了以下链接中提到的异常处理

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

如何将错误消息传递给MVC 5中的错误视图?

It is working fine. But I have requirement to handle 404 Error.

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

How can I do that?

我怎样才能做到这一点?

if I use below code,

如果我使用下面的代码,

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

it works well when any 404 error occurs. But in case any other exception occurs then my error.cshtml call twice and show same exception two times.

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

2 个解决方案

#1


6  

web.config

Turn off custom errors in system.web

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

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

configure http errors in system.webServer

在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>

Create simple error controller to handle those requests ErrorContoller.cs

创建简单的错误控制器来处理这些请求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();
    }
}

configure routes RouteConfig.cs

配置路由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",
        defaults: new { controller = "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}",
        defaults: new { controller = "Error", action = "NotFound" }
    );
}

And finally make sure you have views for the controller actions

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

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

If there are any additional error you want to handle you can follow that pattern and add as needed. This will avoid redirects and maintain the original http error status that was raised.

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

#2


1  

If you will define defaultRedirect attribute for customErrors then error.cshtml will be rendered only once in your case:

如果要为customErrors定义defaultRedirect属性,那么在您的情况下,error.cshtml将只呈现一次:

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

#1


6  

web.config

Turn off custom errors in system.web

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

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

configure http errors in system.webServer

在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>

Create simple error controller to handle those requests ErrorContoller.cs

创建简单的错误控制器来处理这些请求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();
    }
}

configure routes RouteConfig.cs

配置路由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",
        defaults: new { controller = "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}",
        defaults: new { controller = "Error", action = "NotFound" }
    );
}

And finally make sure you have views for the controller actions

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

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

If there are any additional error you want to handle you can follow that pattern and add as needed. This will avoid redirects and maintain the original http error status that was raised.

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

#2


1  

If you will define defaultRedirect attribute for customErrors then error.cshtml will be rendered only once in your case:

如果要为customErrors定义defaultRedirect属性,那么在您的情况下,error.cshtml将只呈现一次:

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