How to handle 404 errors in configuration and code in MVC5?

I implemented exception handling as indicated in the link below

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

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

How can i do this?

if i use below code,

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

It works well when an error occurs 404. But in case of any other exception, my call error.cshtmltwice and shows the same exception two times.

+4
source share
2 answers

web.config

Disable user errors in system.web

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

configure HTTP errors in system.webServer

<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",
        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" }
    );
}

, , , .

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

, , . HTTP, .

+5

defaultRedirect customErrors, error.cshtml :

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

Source: https://habr.com/ru/post/1653398/


All Articles