Skipping IIS Custom Error pages


By default, IIS7 intercepts 4xx and 5xx status responses with its own custom error pages. At work, we have a custom redirection module that checks if the status is 401 Unauthorized and spits javascript to redirect to the log in page. We use javascript in order to preserve # fragment in the return url.

The issue was 401. We set 401 to the response to send a meaninful response. The body contains a javascript redirection chunk. But it is intercepted by IIS7, so the user is not redirected but only see an dumb IIS 401 error page.

dumb_iis7_errror_page

 

 

After some googling, I found two ways to handle the issue. One is to let all response ignore IIS custom error pages. You can do that by setting existingResponse="PassThrough" in the web.config.

[sourcecode language="xml"]
<configuration>
<system.webServer>
<httpErrors existingResponse="PassThrough" />
</system.webServer>
</configuration>
[/sourcecode]

 

The other is to set response.TrySkipIisCustomErrors = true, and then the only that response will be passed through without being intercepted by IIS7 custom error pages.

The second option was appropriate, as we want to pass through only for redirection module.
[sourcecode language="csharp"]
public void OnEndRequest(HttpContextBase context)
{
if (context.Response.StatusCode != 401)
return;

var response = context.Response;
response.TrySkipIisCustomErrors = true;
response.Status = response.Status;
response.StatusCode = (int)HttpStatusCode.Unauthorized;
response.TrySkipIisCustomErrors = true;
response.ClearContent();
response.RedirectLocation = null;
response.Write(_buildClientRedirectionResponse.GetRedirectionScript());
response.End();
}
[/sourcecode]

For me, TrySkipIisCustomErros = true didn't work until you set a value to response.StatusCode. It seems that response.TrySkipIisCustomErrors = true and response.Status = response.Status should be set together.

With the second option, you can benefit from Custom error pages and a temporal pass through for 401 for redirection. Hope this helps.