Set up your own custom 404 and 500 error pages in an ASP.NET MVC site

Most website visitor appreciates a clean understandable error page, therefor  I have set up custom 404 and 500 pages at my main web site.  These are the steps:

  1. Redirect errors by activating custom errors in web.config in the system.websection.
    <customErrors mode="RemoteOnly" defaultRedirect="/Error">
      <error redirect="/Error/NotFound" statusCode="404"/>
      <error redirect="/Error/InternalServerError" statusCode="500"/>
    </customErrors>
    
  2. Remove the error handling filter in Global.asax.cs.
  3. Finally create a controller named Controllers/ErrorController.cs together with related view to handle the action results NotFound and InternalServerError.
    public ActionResult NotFound()
    {
        Response.TrySkipIisCustomErrors = true;
        Response.StatusCode = (int)HttpStatusCode.NotFound;
        return View("NotFound");
    }
    
    public ActionResult InternalServerError()
    {
        Response.TrySkipIisCustomErrors = true;
        Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        return View("InternalServerError");
    }
  4. Congrats, you now have your own custom error pages! Fill the pages with whatever content you want. I decided to use simple images. Don’t ask me about the car wreck, I was also suprised when I bumped into it on a national park hike.

 

More creative solutions can be found here.

Trackback URL: https://codeblog.silfversparre.com/2011/11/how-to-set-up-your-own-custom-404-and-500-error-pages-in-an-asp-net-mvc-site/trackback/