How to Make Custom Error Pages Work in ASP.NET MVC 5

In ASP.NET MVC 5, error pages are used to display error messages to users when an error occurs in an application. By default, ASP.NET MVC 5 provides a default error page that displays a generic error message to users. However, you may want to customize these error pages to provide a better user experience. In this article, we’ll show you how to create custom error pages in ASP.NET MVC 5.

Step 1: Create Custom Error Pages The first step to creating custom error pages in ASP.NET MVC 5 is to create the error pages themselves. To do this, follow these steps:

  1. In the root of your ASP.NET MVC 5 project, create a new folder called “Views/Shared/Error”.
  2. In the “Error” folder, create two new views: “Error.cshtml” and “NotFound.cshtml”.
  3. In each view, customize the HTML and CSS to your liking. For example, you might want to include your company’s logo or a message to users.

Step 2: Configure Custom Error Pages on the Web.config File After creating your custom error pages, you need to configure your application to use them. To do this, you will modify the Web.config file in your ASP.NET MVC 5 project. Here are the steps:

  1. Open the Web.config file in your ASP.NET MVC 5 project.
  2. Locate the <system.web> element in the file.
  3. Add the following elements within the <system.web> element:
<customErrors mode="On" defaultRedirect="~/Error">
  <error statusCode="404" redirect="~/Error/NotFound" />
  1. Save the changes to the Web.config file.

In the code above, we’re telling ASP.NET MVC 5 to use our custom error pages when an error occurs. Specifically, we’re telling it to redirect to the “Error” view by default and to redirect to the “NotFound” view when a 404 error occurs.

Step 3: Test Your Custom Error Pages To test your custom error pages, you can intentionally cause an error in your ASP.NET MVC 5 application. For example, you can try to access a non-existent page on your website to trigger a 404 error. When you do, you should see your custom error page instead of the default error page provided by ASP.NET MVC 5.

Conclusion Custom error pages are an important part of any ASP.NET MVC 5 application. By following the steps outlined in this article, you can create custom error pages that provide a better user experience for your application’s users.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: