If you are like me you will probably have tried (and failed) many times to implement custom error page handling in your MVC application many times.

I have read countess articles, tried many different methods, and non of them worked (fully)…until now*.

Well actually it was a combination of the 2 articles below that finally got me to a happy place:

Please note that this is geared towards 404 pages but applies to other status codes. The goals here are:

  1. You want your url to be preserved (for a 404 error)

  2. You want a 404 status code to be returned to the browser

  3. You want a custom error page displayed.

Step 1: Get rid of HandleErrorAttribute

publicstaticvoid RegisterGlobalFilters(GlobalFilterCollection filters) { //filters.Add(new HandleErrorAttribute()); }

 That’s right, just comment it out. ## Step 2: Create yourself a 404.aspx page The basic page below will get you started and 2 things to note. You need an .aspx (weird I know) and you need to return the StatusCode for the Response, in this case 404. <% Response.StatusCode = 404 %>DOCTYPEhtml><htmllang="en"><head><metacharset="utf-8"/><title>404 Page Not Foundtitle>head><body><h1>404 Page Not Foundh1>body>html>

Step 3: Create yourself a Controller.cs file as shown below

using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace YourApplication { publicclass Controller : System.Web.Mvc.Controller { protectedoverridevoid HandleUnknownAction(string actionName) { Response.StatusCode = 404; } } }

This was the magic from the second article which solved issues I had with 404 errors and helped me achieve the 3 goals above.

Step 4: Add the config

Add this to your section of web.config

"On" redirectMode="ResponseRewrite"> "404" redirect="~/404.aspx"/>

And believe it or not that seems to work for pretty much all the scenarios I need to cover such as:





  • except this one doesn’t but does give me a 404, just doesn’t hit the 404.aspx page Sad smile