Creating a 404 Rule in ASP.NET Core

2016-02-13

Creating a NotFound / 404 rule within ASP.NET Core is quite simple, and once you've created that you'll be able to create custom error pages for all error status codes.

  • 1. Update the Startup.cs Located at the root of any ASP.NET Core application is the Startup.cs file containing all the necessary bootstrap code.
  • 2. Update the Configure method with the following:
 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
 { 

 ... 

   if (env.IsDevelopment()) 
   { 

     app.UseDeveloperExceptionPage(); 

     app.UseBrowserLink(); 

   } 

   else 
   { 

     //redirects all errors given their error code 

     app.UseStatusCodePagesWithReExecute("/error/{0}"); 

     app.UseApplicationInsightsExceptionTelemetry(); 

   }  

   ... 

 }

The above code will now redirect all errors, e.g. a 404 not found error will get redirected to /error/404. Now we need to setup the routes and controllers to handle these requests.

  • 3. Update the routing rules

We now need a routing rule to handle all the potential error redirects.

Update the routing rules with the following:

      ... 

 //This routes specifically handles 404 not found requests 

 routes.MapRoute( 

 name: "Error-404-Route", 

 template: "error/404", 

 defaults: new { controller = "Error", action = "NotFound" } 

 ); 


 routes.MapRoute( 

 name: "Error-StatusCode-Route", 

 template: "error/{statusCode}", 

 defaults: new { controller = "Error", action = "InternalServerError" } 

 ); 

 

 ...
  • 4. Create an error controller

Create an error controller in a new file ErrorController.cs with the following code, making sure you take any areas into account if applicable

 using Microsoft.AspNetCore.Mvc; 

 namespace Test.Controllers 
 { 

 public class ErrorController : Controller 
 { 

   public IActionResult InternalServerError(int statusCode) 
   { 

     ... 

     return View("~/Views/Error/500.cshtml"); 

   } 


   public IActionResult NotFound() 
   { 

     ... 

     return View("~/Views/Error/404.cshtml"); 

   }

 } 

 }
  • 5. Create the associated views

Now we need to create error views for the associated errors, i.e. ~/Views/Error/404.cshtml

<div>404 Not Found<div/>