Custom 404 Errors and MVC 3/4

Mar 5, 2013 at 5:58 PM
How do I make custom 404 error pages (and other HTTP errors) work with code routing?

My existing project registers a custom filter error handler to handle some error logging and has an Error controller with Actions (and corresponding Views) for the various errors where I want to use customized pages.

In web.config, I have the following...
    <customErrors mode="On" defaultRedirect="/Error">
      <error statusCode="404" redirect="/Error/NotFound"/>
      <error statusCode="403" redirect="/Error/Forbidden"/>
Without MVCCodeRouting configured, this all works like a charm. If someone enters an invalid URL, say /MissingPage or /NonExistingPage.aspx, then my error filter captures the 404, does it's logging, and then displays my custom Error/NotFound page.

However, if I enable MVC Code Routing, only the second example is successfully caught by my filter and displays the Error/NotFound page. The first example, which is missing any standard ASP file extension, simply shows the IIS HTTP Error 404.0 - Not Found page. My custom filter is never called, Application_Error is never called, and the error page in web.config is never displayed.

Mar 5, 2013 at 6:11 PM
This is because, without MvcCodeRouting, /MissingPage is handled by your routes, then an exception is thrown if the controller/action is not found. With MvcCodeRouting, the routes are more "strict", by using constraints it prevents handling /MissingPage, hence you get an IIS error instead of an ASP.NET error.

You should configure error pages for non ASP.NET requests, something like this:
   <httpErrors errorMode="Custom">
      <remove statusCode="404"/>
      <error statusCode="404" path="/Error/NotFound" responseMode="ExecuteURL"/>
Marked as answer by maxtoroq on 10/15/2013 at 9:21 AM
Mar 7, 2013 at 11:47 PM
Right...that makes sense.

I had to rework a few things in my logging to account for this difference, but I got it working. Previously, I was relying on the fact that missing actions generated exceptions, which I could handle in a custom HandleErrorAttribute. I used this distinction to help weed through 404 situations that were likely a result of bad code vs all the junk that gets sent my way from the wild (those didn't trigger my attribute). With the httpErrors solution, that all gets routed the same place now.

Oct 24, 2013 at 11:46 AM
The problem is that Application_Error still not called. Even in case of custom pages. So if we want to save exception info to show it on page we haven't such possibility.