After having posted Html Conventions for FubuMVC, this post will definitely serve as a contrast as it will be about ASP.NET MVC. This time, I hope to help those looking to handle HTTP errors globally in either the Global.aspx file or through and Http Module. There are a myriad of posts online about performing this very task and I, personally, spent considerable time looking at the different the different options that we have.

  • The first and most popular option if you're familiar with classic ASP.NET Web Forms development is the config section. Let me encourage you not to waste your time with this option. When using you're encouraged to redirect when the web stack encounters an exception. This is wrong because the original HTTP code should be preserved instead of the HTTP 302 redirect code. Also, the original Url should also be preserved. For instance, if you go to the original Url and 404 code is preserved while the not found message is displayed. This is the desirable result.
  • The second and also correct way is to use the config section through the web.config file or the IIS Http Errors option page. This options does handle the errors correctly, keeping the original Url with the Http error code. However, with IIS 7.5, it's awkward to configure and is also difficult to render custom error information that you may want to render in the page.
  • The third option, and the one that I will discuss in detail, lets you handle Http errors globally through the Global.asax file or an Http Module. This method does have several advantages over the others, specially that you will be in full control of how the errors are handled and error pages rendered. In the Global.asax, you can have a simple error handling code like the following:
You may also wish to put in logging or any other general exception handling features. Alternatively, you can write that same code within an Http Module, circumventing the Global.asax file altogether.

The actual magic is all contained in the HttpContextBase extension, specifically RenderViewToHttpContextResponse. This extension method takes in the view name to render, and optionally, the controller name plus any ViewData that we may wish to pass in.

The last remaining dependent code is the ExceptionExtensions for detecting whether an exception is an HTTP 404 Not Found. That is simply the following:

It is important to note that if any part of the code within the Application_Exception method fails, you will need to resort to a custom IIS Error, but hopefully, the code within that method is virtually fail safe.