Custom 404 page ignored by IIS 7

If your IIS does not display your own custom error page, this might be the problem – and the solution:

I recently had to implement a custom 404 error page. The code for that is pretty simple. In the web.config, the custom 404 error page is added:

<customErrors mode="Off">
  <error statusCode="404" redirect="/components/Error/404.aspx" />
</customErrors>

And the page is requested to return a 404 not found:

protected void Page_Load(object sender, EventArgs e)
{
  Response.StatusCode = 404;
  Response.StatusDescription = "Page not found";
  Response.Flush();
}

Here is the problem: The code worked fine on my Windows 7 developer machine’s localhost, but when I copied the code to my Windows 2008 server, the IIS refused to call my custom page, displaying the default 404 error page instead.

Here is the catch: The Windows 2008 server is running the latest IIS 7.5, and this version will by default “override” the HTTP response with its default error pages if the page returns a HTTP error status code (like 404, or 500).

Here is the solution: .NET 3.5 has a new property called Response.TrySkipIisCustomErrors that will, if set to true, instruct IIS 7.5 to ignore it’s own default error pages, allowing me to use my own. The code change is very small, but highly effective:

protected void Page_Load(object sender, EventArgs e)
{
  // Allow me to use my own error page:
  Response.TrySkipIisCustomErrors = true;
  Response.StatusCode = 404;
  Response.StatusDescription = "Page not found";
  Response.Flush();
}

Violá. A true WTF moment solved with one line of code.

Advertisements

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, c#, General .NET and tagged , , . Bookmark the permalink.

3 Responses to Custom 404 page ignored by IIS 7

  1. Hi Brian, Thanks for sharing.
    For general information the same can also be optained with:

    Regards,
    Jan

  2. Pingback: Sitecore 404 without 302 | Brian Pedersen's Sitecore and .NET Blog

  3. Abraham Kifle says:

    This is exactly what I have been looking for. I was playing with ihttphandler as a proxy and wanted to pass the custom 404 page of the target server. Even though I read the response stream, IIS was responding with “The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.”

    Many Thanks.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s