Handling 404 errors in MVC applications

This page describes the best practices for creating “404 Not Found” pages when developing Kentico sites using the MVC development model. We recommend handling 404 errors through IIS, which allows you to return your “Not Found” page in the following scenarios:

  • The URL does not match any route in the routing table
  • A suitable controller is not found
  • A suitable controller action is not found
  • The status code of the server’s response is 404

To set up a 404 error page, you need to do the following steps:

  1. Set up the error handling via IIS in the Global.asax file.
    • The server’s IIS must have the Common HTTP Features -> HTTP Errors feature installed (in the operating system’s features).
  2. Create a 404 Not Found page as:
  3. Add an httpErrors element that specifies the path to your 404 page to the project’s Web.config file.

Setting up 404 error handling via IIS

Open the project’s ~/Global.asax file and add an Application_Error() method to the application class:

Global.asax



        protected void Application_Error()
        {
            // Sets 404 HTTP exceptions to be handled via IIS (behavior is specified in the "httpErrors" section in the Web.config file)
            var error = Server.GetLastError();
            if ((error as HttpException)?.GetHttpCode() == 404)
            {
                Server.ClearError();
                Response.StatusCode = 404;
            }
        }



Creating MVC pages for 404 errors

The first approach is to create a controller with actions handling error states and reference the respective action in the Web.config. This approach enables you to use all MVC features when creating the error page.

  1. Create a view that presents the content required by your site’s 404 page according to the general MVC best practices.

  2. Create a controller for the 404 error page.

    • The controller needs to define an action that sets the response status code to 404.

    • The action must be accessible through a route registered in your project’s routing table.

      Controller: NotFound action
      
      
      
                public ActionResult NotFound()
                {
                    Response.StatusCode = 404;
      
                    return View();
                }
      
      
      
        
  3. Modify the project’s Web.config file and add 404 error handling under the system.webServer node:

    Web.config
    
    
    
     <system.webServer>
         ...
         <httpErrors errorMode="Custom" existingResponse="Auto">
             <remove statusCode="404" subStatusCode="-1" />
             <error statusCode="404" path="/HttpErrors/NotFound" responseMode="ExecuteURL"/>
         </httpErrors>
         ...
     </system.webServer>
    
    
     

    Path attribute value

    The path attribute of the <error> element needs to match the route of the NotFound action in the controller created in the first step, including the application path if the application is running in a virtual directory. For example, if the URL of the 404 error page is http://www.example.com/MyWebSite/ErrorPages/NotFound, the path value would be “/MyWebSite/ErrorPages/NotFound”, including the starting slash.

Now whenever a live site visitor requests an invalid URL, the content defined in your view is displayed.

Creating static HTML pages for 404 errors

A different approach is to create a static HTML page and reference it in the Web.config. Choosing this approach may be easier in some cases, but you may need to manually style the page so that it matches your site’s layout.

  1. Create a HTML file within your project, with the content required by your site’s 404 page.

  2. Modify the project’s Web.config file and add 404 error handling under the system.webServer node:

    Web.config
    
    
    
     <system.webServer>
         ...
         <httpErrors errorMode="Custom" existingResponse="Auto">
             <remove statusCode="404" subStatusCode="-1" />
             <error statusCode="404" path="HttpErrors\404.html" responseMode="File"/>
         </httpErrors>
         ...
     </system.webServer>
    
    
     

    Path attribute value

    The path attribute of the <error> element needs to be a file path relative to the application root. The path must be delimited by backslashes (\) and cannot start with a backslash.

Now whenever a live site visitor requests an invalid URL, the content defined in your HTML file is displayed.