Posts Tagged ‘c#’

Custom Error Handler in IIS7

Thursday, April 2nd, 2009

Introduction

During the development of SKUM3 some problems have not manifested themselves while developing for one simple reason: Visual Studio 2008 uses a version of IIS 6 as a development server, but our final setup will be an IIS 7 server. The differences between these two version are significant enough to cause headaches.

One such headache is the inability to debug code running on the remote server. This combined with differences in how errors are handled, both in the setup in the web.config file, and in the way a custom error handler is called, produced a very difficult to solve problem. Also a lack in documentation is partly to blame.

The problem

web.config differences.

IIS 7 version:

<httpErrors>
    <remove statusCode="404" subStatusCode="-1" />
    <error statusCode="404" prefixLanguageFilePath=""
        path="/path/to/handlerwebservice"
        responseMode="ExecuteURL" />
</httpErrors>

 IIS 6 version:

<customErrors mode="On">
    <error statusCode="404" redirect="webservices/media/image"/>
</customErrors>

With the IIS 6 version all 404 errors are redirected to webservices/media/image?aspxerrorpath=original/path. In IIS 7 though this querystring parameter is missing so what to do?

The Solution

Well, microsoft is not very helpful and I tried asking my question to the Internet but as I didn’t receive any answers I just tried changing

context.Request.Path

to

context.Request.RawUrl

Resulting in this code to handle the differences:

string requestpath;

if(context.Request.QueryString.AllKeys.Contains("aspxerrorpath"))
{
    requestpath = context.Request.QueryString["aspxerrorpath"];
}
else
{
    requestpath = context.Request.RawUrl;
}

This seemed to have the desired effect. The difference between these two are that RawUrl contains the requested path unaltered by redirection or anything else and Path is the Url after any redirection. I had forgotten this minor detail even though I’ve used it in the breadcrumb method to split an original path up into individual pieces, after the request had been redirected by our UrlRewriter.

If you are getting weird errors about httpErrors being locked down use a cheat code

%windir%\system32\inetsrv\appcmd.exe unlock config -section:system.webServer/httpErrors