Many moons ago, I wrote a blog post about properly handling 404 (page not found) errors with ASP.NET. But an often overlooked and underused approach to error handling is the custom 500 error page. For those not familiar with a 500 error, it is the error that occurs when an exception is made. An exception could be anything from incorrect logic introduced into the code by the developer (not me of course) to malicious data entered by a user into a form field. If the developer chooses not to implement a custom 500 error page, the end user will be presented with an often very unpicturesque screen containing information about the exception. Often, this information can be very revealing and can give a hacker just the right amount of information they need to compromise your website.
The solution to all of this is to properly configure your web application to display a page that is more user-friendly, pleasing to the eyes and one that conveys a custom message to the end user. Consider our custom 500 error page for example:
OK, so how do we achieve this correctly in IIS 7 and above? Sometimes our friends at Microsoft try to make things easy for us, but in the end just end up bumbling things by adding code we do not need to our website’s configuration file (web.config). The best way to deal with this, I’ve found, is not to use the GUI that is presented to us in IIS and just do things the old-fashioned way… manually. I cannot tell you how many times I have had a perfectly configured site, then made a simple change in IIS only to have something else completely overwritten that had nothing to do with what I was editing in the first place. Anyway, the solution is actually simple. Simply add the following lines to your web.config file in the correct location:
<customErrors mode=”On” redirectMode=”ResponseRewrite”>
<error statusCode=”500″ redirect=”~/errorpages/500.aspx” />
Now that is not what IIS will output for you, but believe me, that is all the code you will need to achieve the desired result. IIS will actually add a bunch of code in the system.webServer node that could possibly interfere with other error handling rules, such as the custom 404 rule. The ResponseRewrite value for the redirectMode property will not redirect the user to the error page, but rather leave the URL intact while displaying the contents of the error page. This is another safeguard measure so you do not reveal the location of the error page to the end user. In my next blog, I will expand upon this post and demonstrate how to integrate custom 404 and custom 500 errors that properly handle static and dynamic file types.