Failed to load resource the server responded with a status of 404 () asp.net core

Failed to load resource the server responded with a status of 404 () asp.net core

By , Columnist, InfoWorld |

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

Failed to load resource the server responded with a status of 404 () asp.net core
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. 

Failed to load resource the server responded with a status of 404 () asp.net core
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?

Failed to load resource the server responded with a status of 404 () asp.net core
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.

Failed to load resource the server responded with a status of 404 () asp.net core
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.

How to do more in ASP.NET Core:

  • How to use dependency injection in action filters in ASP.NET Core 3.1
  • How to use the options pattern in ASP.NET Core
  • How to use endpoint routing in ASP.NET Core 3.0 MVC
  • How to export data to Excel in ASP.NET Core 3.0
  • How to use LoggerMessage in ASP.NET Core 3.0
  • How to send emails in ASP.NET Core
  • How to log data to SQL Server in ASP.NET Core
  • How to schedule jobs using Quartz.NET in ASP.NET Core
  • How to return data from ASP.NET Core Web API
  • How to format response data in ASP.NET Core
  • How to consume an ASP.NET Core Web API using RestSharp
  • How to perform async operations using Dapper
  • How to use feature flags in ASP.NET Core
  • How to use the FromServices attribute in ASP.NET Core
  • How to work with cookies in ASP.NET Core
  • How to work with static files in ASP.NET Core
  • How to use URL Rewriting Middleware in ASP.NET Core
  • How to implement rate limiting in ASP.NET Core
  • How to use Azure Application Insights in ASP.NET Core
  • Using advanced NLog features in ASP.NET Core
  • How to handle errors in ASP.NET Web API
  • How to implement global exception handling in ASP.NET Core MVC
  • How to handle null values in ASP.NET Core MVC
  • Advanced versioning in ASP.NET Core Web API
  • How to work with worker services in ASP.NET Core
  • How to use the Data Protection API in ASP.NET Core
  • How to use conditional middleware in ASP.NET Core
  • How to work with session state in ASP.NET Core
  • How to write efficient controllers in ASP.NET Core

Joydip Kanjilal is a Microsoft MVP in ASP.Net, as well as a speaker and author of several books and articles. He has more than 20 years of experience in IT including more than 16 years in Microsoft .Net and related technologies.

Copyright © 2020 IDG Communications, Inc.