Joydip Kanjilal
Contributor

How to handle 404 errors in ASP.NET Core MVC

how-to
Jun 01, 20207 mins
C#Microsoft .NETSoftware Development

Take advantage of ASP.NET Core middleware to handle 404 errors more gracefully in ASP.NET Core MVC

error 404 web browser
Credit: Thinkstock

ASP.NET Core MVC is the .NET Core counterpart of the ASP.NET MVC framework for building cross-platform, scalable, high-performance web applications and APIs using the Model-View-Controller design pattern. Surprisingly, although ASP.NET Core provides plenty of options for handling 404 errors gracefully, the ASP.NET Core MVC runtime doesn’t take advantage of them by default.

As a result, when a web page is not found and a 404 error is returned by the application, ASP.NET Core MVC presents only a generic browser error page (as shown in Figure 1 below). This article discusses three options in ASP.NET Core we can use to handle 404 errors more gracefully.

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here.

Create an ASP.NET Core MVC project

First off, let’s create an ASP.NET Core project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new ASP.NET Core project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web Application” from the list of templates displayed.
  4. Click Next. 
  5. In the “Configure your new project” window shown next, specify the name and location for the new project.
  6. Click Create.
  7. In the “Create a New ASP.NET Core Web Application” window, select .NET Core as the runtime and ASP.NET Core 3.1 (or later) from the drop-down list at the top.
  8. Select “Web Application (Model-View-Controller)” as the project template to create a new ASP.NET Core MVC application.
  9. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.
  10. Ensure that Authentication is set to “No Authentication” as we won’t be using authentication either.
  11. Click Create.

Following these steps will create a new ASP.NET Core MVC project in Visual Studio 2019. We’ll use this project to illustrate our 404 error handling options in the subsequent sections of this article.

When you execute the ASP.NET Core MVC project we’ve created in the preceding section, you will see the home page of the application together with the welcome message as shown in Figure 1 below. 

aspnet core mvc 404 errors 01 IDG

Figure 1: The default home page in ASP.NET Core MVC. 

Now let’s try to browse a web page that doesn’t exist. To do this, type http://localhost:6440/welcome in the address bar of your browser while the application is in execution. When the ASP.NET Core MVC engine fails to locate the resource for the specified URL, a 404 error will be returned and you will be presented with the following error page. That’s not very elegant, is it?

aspnet core mvc 404 errors 02 IDG

Figure 2: The default 404 error page displayed by ASP.NET Core MVC for a non-existent web page.

Check Response.StatusCode in ASP.NET Core MVC

There are several ways in which you can improve on this generic error page. A simple solution is to check for the HTTP status code 404 in the response. If found, you can redirect the control to a page that exists. The following code snippet illustrates how you can write the necessary code in the Configure method of the Startup class to redirect to the home page if a 404 error has occurred.

 app.Use(async (context, next) =>
    {
        await next();
        if (context.Response.StatusCode == 404)
        {
            context.Request.Path = "/Home";
            await next();
        }
    });

Now if you execute the application and try to browse the URL http://localhost:6440/welcome, you will be redirected to the home page of the application.

The complete code of the Configure method is given below for your reference.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.Use(async (context, next) =>
            {
                await next();
                if (context.Response.StatusCode == 404)
                {
                    context.Request.Path = "/Home";
                    await next();
                }
            });
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }

Use UseStatusCodePages middleware in ASP.NET Core MVC

A second solution for handling 404 errors in ASP.NET Core is by using the built-in UseStatusCodePages middleware. The following code snippet shows how you can implement StatusCodePages in the Configure method of the Startup class.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseStatusCodePages();
            //Other code
        }

Now when you execute the application and browse to the non-existent resource, the output will be similar to Figure 3.

aspnet core mvc 404 errors 03 IDG

Figure 3: The ASP.NET Core StatusCodePages middleware in action. 

Use UseStatusCodePagesWithReExecute middleware in ASP.NET Core MVC

You can take advantage of the UseStatusCodePagesWithReExecute middleware to handle non-success status codes in cases where the process of generating the response has not been started. Hence this middleware will not handle HTTP 404 status code errors — rather, when a 404 error occurs the control will be passed to another controller action to handle the error.

The following code snippet illustrates how you can use this middleware to redirect to another action method.

app.UseStatusCodePagesWithReExecute("/Home/HandleError/{0}");

Here’s what the action method would look like.

[Route("/Home/HandleError/{code:int}")]
public IActionResult HandleError(int code)
{
   ViewData["ErrorMessage"] = $"Error occurred. The ErrorCode is: {code}";
   return View("~/Views/Shared/HandleError.cshtml");
}

I leave it to you to create the HandleError view to display the error message.

Finally, you might want to create views specifically for an error code. For example, you might create views such as Home/Error/500.cshtml or Home/Error/404.cshtml. You could then check the HTTP error code and redirect to the appropriate error page.

Yet another way of handling page not found errors is by using a custom view and setting the error code appropriately. When an error occurs in your application, you could redirect the user to the appropriate error page and display your custom error message describing the error.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author