How to handle 404 errors in ASP.NET Core

By FoxLearn 1/8/2025 4:41:06 AM   127
ASP.NET Core MVC is a framework for building cross-platform, scalable web applications and APIs using the Model-View-Controller pattern.

Despite offering various methods for handling 404 errors, the framework does not use them by default. As a result, when a page is not found, it shows a generic browser error page instead of a custom 404 error page.

When the ASP.NET Core MVC project is executed, the home page with a welcome message appears.

If you attempt to browse a non-existent web page, a 404 error will occur. For example, You can enter "http://localhost:6120/welcome" in your browser's address bar while the application is running. If the ASP.NET Core engine cannot find the resource for the given URL, a 404 error will be returned, and you will see the error page.

Checking Response.StatusCode in ASP.NET Core

There are several ways to improve the generic error page.

One simple approach is to check for a 404 HTTP status code in the response. If found, you can redirect the user to an existing page.

The following code snippet demonstrates how to implement this in the Configure method of the Startup class to redirect to the home page in case of a 404 error:

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

With this code, if you run the application and attempt to browse to "http://localhost:6120/welcome", you will be redirected to the home page.

Using UseStatusCodePages middleware in ASP.NET Core

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 to implement StatusCodePages in the Configure method of the Startup class:

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

With this implementation, when you execute the application and try to access a non-existent resource, the output will display a status code page.

Using UseStatusCodePagesWithReExecute Middleware in ASP.NET Core

You can also use the UseStatusCodePagesWithReExecute middleware to handle non-success status codes when the response process hasn't started yet. This middleware does not handle HTTP 404 errors directly; instead, it passes control to another controller action to handle the error.

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

The action method for handling the error would look like this:

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

You can create the HandleError view to display the error message.

Additionally, you may create specific views for error codes, such as Home/Error/500.cshtml or Home/Error/404.cshtml, and then check the HTTP error code to redirect to the corresponding error page.

Another approach to handling page-not-found errors is by using a custom view and setting the error code accordingly. When an error occurs in your application, you can redirect the user to a specific error page and display a custom message that explains the error.