How to create custom 404 error handler in ASP.NET MVC

Custom 404 error handler – 404 Error refer to a not found resource/URL . Here’s how a default 404 Error notification looks in ASP.NET MVC.

custom 404 error handler

ASP.NET MVC has his own custom error handler that can be enable inside Web.Config file from your solution explorer.

Let’s Start:

First, to enable error redirection modify your Web.Config file.Search for <system.web> in your Web.Config and Add the code below inside the <system.web></system.web>.

Second, navigate to your Controller folder and create a controller ErrorController.This will serve as our custom error handler. Inside this controller create an action result method, let’s named it as NotFound this will return our custom view for 404 error.

Third, create a view for NotFound action result method.By default view for controller can be manually created inside View->Error folder.  Or by simply right clicking on your Not Found method inside ErrorController and selecting Add View.

custom 404 error handler

Custom Error Preview:

custom 404 error handler

 

Note: I used Bundle Config inside App_Start folder to call my custom style.css file.

custom 404 error handler

To add bundle you can simply copy the code below into your BundleConfig file where ~/Content/style.css is the location of your stylesheet and ~/Content/Custom/Error  is the name of your bundle.

  • Add(new StyleBundle(“~/Content/Custom/Error”).Include(

“~/Content/style.css”));

To call this bundle you can simply use @Styles.Render(“~/Content/Custom/Error”)

Code:

To add designed to the view we can also add icons. In my case i used the image below. Which i included inside image folder.  And used <img src=”~/images/smile.png” /> to include image in my view.

custom 404 error handler

Fourth, Create styles for your view. In my case I create a file name style.css inside content folder from solution explorer.

custom 404 error handler

Style.css Code:

And we are done. Every time a URL is invalid this error notification will appear instead of the default 404 error notification.

custom 404 error handler

Thank you for reading!! Happy coding!!

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *