ASP.NET MVC 5 custom errors

Posted

ASP.NET MVC 5 allows you to define custom errors in the config file, similar to the following:

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

This usually works, but depending on the version of IIS, you may also need to set TrySkipIisCustomErrors on the Response.

public ActionResult NotFound()
{
    Response.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
    Response.TrySkipIisCustomErrors = true;

    return View();
}

Author