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.
