top of page
Writer's pictureThe Tech Platform

How to handle 404 errors in ASP.NET Core MVC

Updated: Feb 28, 2023


In ASP.NET Core MVC, a 404 error (also known as HTTP error 404) occurs when the server cannot find the requested resource or page. This can happen for various reasons, such as a missing file or a mistyped URL. When a 404 error occurs, the server returns an HTTP response code of 404 to the client, indicating that the requested resource is not available on the server. In this tutorial, we will learn how to handle 404 errors in ASP.NET Core MVC and provide a custom error page to the user.


In ASP.NET Core MVC, a 404 error can be triggered when a user tries to access a URL that does not correspond to any route defined in the application's routing configuration. For example, if a user tries to access a URL that does not match any of the controller action methods, the server will return a 404 error.


By default, when a 404 error occurs in ASP.NET Core MVC, the server returns a generic error message to the user. However, it is possible to customize the error handling behavior to provide a more informative and user-friendly experience to the user, such as displaying a custom error page or redirecting the user to a specific URL.


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.


STEP 1: Launch the Visual Studio IDE.


STEP 2: Click on “Create new project.”


STEP 3: In the “Create new project” window, select “ASP.NET Core Web Application” from the list of templates displayed.


STEP 4: Click Next.


STEP 5: In the “Configure your new project” window shown next, specify the name and location for the new project.


STEP 6: Click Create.


STEP 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.


STEP 8: Select “Web Application (Model-View-Controller)” as the project template to create a new ASP.NET Core MVC application.


STEP 9: Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.


STEP 10: Ensure that Authentication is set to “No Authentication” as we won’t be using authentication either.


STEP 11: Click Create.


Handling 404 Errors in ASP.NET Core MVC

Step 1: Create a Custom Error Page

The first step in handling 404 errors is to create a custom error page that will be displayed to the user when a 404 error occurs. To create a custom error page, follow these steps:


STEP a: In the "Views/Shared" folder, create a new view called "Error.cshtml". This view will be used to display the error message to the user.


STEP b: Add the following code to the "Error.cshtml" view:

@model Microsoft.AspNetCore.Diagnostics.StatusCodeReExecuteFeature  

<h1>Error</h1>
<p>We're sorry, but the page you requested could not be found.</p>

This code displays a simple error message to the user, indicating that the requested page could not be found.

Step 2: Configure the Application to Handle 404 Errors

The next step is to configure the ASP.NET Core MVC application to handle 404 errors and redirect the user to the custom error page. To do this, follow these steps:

STEP a: Open the "Startup.cs" file in the root of the project.


STEP b: In the "Configure" method, add the following code:

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

This code sets up the application to use a custom error page for all 404 errors. The "{0}" parameter represents the HTTP status code that caused the error.

STEP c: Add a new action to the controller to handle the custom error page:

[Route("Error/{statusCode}")] 
public IActionResult Error(int statusCode) 
{     
    var feature = HttpContext.Features.Get<IStatusCodeReExecuteFeature>();      
    
    return View(new ErrorViewModel { StatusCode = statusCode, OriginalPath = feature?.OriginalPath }); 
} 

This code defines a new action in the controller that handles the custom error page. The action takes an integer parameter, which represents the HTTP status code that caused the error. The action also uses the IStatusCodeReExecuteFeature feature to retrieve the original URL path that caused the error. This information is used to display a more informative error message to the user.

STEP d: Create a new view model called "ErrorViewModel":

public class ErrorViewModel 
{     
    public int StatusCode { get; set; }     
    public string OriginalPath { get; set; } 
} 

This view model is used to pass data to the custom error page view.

STEP e: Modify the "Error.cshtml" view to display the error message and the original path:

@model ErrorViewModel  

<h1>Error</h1>
<p>We're sorry, but an error has occurred.</p>
<p>Status code: @Model.StatusCode</p>
<p>Original path: @Model.OriginalPath</p>

This code displays the error message, status code, and original path to the user.

Step 3: Test the 404 Error Handling

To test the 404 error handling, simply try to access a page that does not exist on the server. The application should display the custom error page with the error message and original path information.

Conclusion

In this tutorial, we learned how to handle 404 errors in ASP.NET Core MVC and provide a custom error page to the user. We created a custom error page, configured the application to use it for all 404 errors, and added an action to the controller to handle the custom error page. By following these steps, you can provide a more robust error-handling experience for your users, ensuring that they receive informative and helpful error messages when something goes wrong on your site.

Commentaires


bottom of page