Gaurav123
Gaurav123

Reputation: 5219

How to handle 404 error in config and code in MVC5?

I have implemented exception handling as mentioned in below link

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

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

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.

Upvotes: 11

Views: 9758

Answers (2)

Ankit K
Ankit K

Reputation: 1326

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

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

Upvotes: 2

Nkosi
Nkosi

Reputation: 247561

web.config

Turn off custom 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>

Create simple error controller to handle those requests 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

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.

Upvotes: 12

Related Questions