MVC 5 How To Show Custom Error Pages

posted on 11/29/2014 8:13 AM by Eric Butler


While working on Neptune Century's site redesign, I stumbled upon some issues trying to show custom error pages for 404 and 500 errors. The 500 error is relatively easy to deal with, but 404 was a bit trickier... that is until I realized how to do it with MVC and IIS 8+.

The first thing I tried was the ye old customErrors section in System.Web. It did what is was supposed to do, that is redirect the user to a friendly 404 error page, but the problem with that approach was that the response code was set to a 302 redirect. That is not a very good solution for SEO optimization. We want the page/url we request to be delivered as a 404 response, not a redirect. Here is an example of what I mean:


As you can see in the image above, the customErrors section causes a 302 redirect. The actual page Error/NotFound contains the 404. This is not what we want! First off, we want the url in the browser to stay the same, but in this case, it changes to Error/NotFound?aspxerrorPath=/Home/FooBar. Ewwwww.

In order for us to get a proper status code returned to the browser, and keep our original URL, we need to add a section to the web.config. I also commented out the customErrors section.


When adding this section to your site, keep in mind that if you want to show custom errors while you are developing, you need to set errorMode="Custom". This will allow you to test your error page. Set it to DetailedLocalOnly when you want to see the detailed errors on your development machine.

Now, in our ErrorController, we define our actions:


Make sure to set the Respone.StatusCode to 404 or the browser will get a 200 (success).

One other thing to note; when I added the above to my web.config. At first it didn't work. I had to add the existingResponse="Replace" attribute. This replaces the default 404 / 500 response with your custom content.

So, what does it look like now?


And a quick check of the developer tools (F12)


Now you can see that our response code is 404 for the invalid url, and not a 302 redirect! Yay!

Want to try this out yourself? Head over to the GitHub page and download or clone the repo. Then run the solution in Visual Studio 2013.

Get This Demo




As a thank-you, please consider sending a small donation. You can contribute as much as you'd like.

Comments

Log in to leave a comment

Log In