Custom Error for non ASP.NET files

Custom errors are helpful in website to provide information to the users with more friendly errors. I needed to do the same with my blog. But unfortunately only .aspx, .axd and other asp.net files would show the custom error. So navigating to a url (http://blog.prabir.me/badurl.html) that doesn’t exist and is not registered by asp.net would lead me to the following error which was not what I wanted.

image

I needed to extend it in order to support extension less url or other url that are not handled by asp.net.

By default BlogEngine provides me with the following custom error which only works for asp.net files.

<customErrors mode="RemoteOnly" defaultRedirect="~/error404.aspx">
    <error statusCode="404" redirect="~/error404.aspx"/>
</customErrors>

The solution was to modify the web.config, rather add the following piece of code to my <system.webServer> so that it gets handled by IIS (This requires IIS7).

<httpErrors errorMode="Custom" existingResponse="Replace" >
    <remove statusCode="404"/>
    <error statusCode="404" path="/error404.aspx" responseMode="ExecuteURL"/>
</httpErrors>

Now even non asp.net files are handled like shown below.

image

Note: In path=”/error404.aspx”, it start with / not ~/. ASP.NET users should be careful with this otherwise it will not work.

For more information on <httpErrors> refer to the MSDN Library.


blog comments powered by Disqus