ASP.NET: Prevent IIS 7.5 from overriding custom error pages with IIS default error pages

I’ve created a ASP.NET MVC 3 application with custom error pages for HTTP status code 404 (“Not Found”) and 500 (“Internal Server Error”). I registered my custom pages in the Web.config as follows:

<configuration>
  <system.web>
    <customErrors defaultRedirect="/Error/InternalServerError" mode="RemoteOnly">
      <error redirect="/Error/NotFound" statusCode="404" />
      <error redirect="/Error/InternalServerError" statusCode="500" />
    </customErrors>
  </system.web>
</configuration>

After deploying my ASP.NET application to an IIS 7.5 web server I was surprised by the fact that the IIS web server seems to override my error page configuration: Instead of showing my (custom) error pages the web server returns the default IIS error pages. After some research I found out, that by default the IIS “overrides” the HTTP response with its default error pages if one returns an HTTP (error) status code (like 404 or 500). One solution to disable this behavior is to set Response.TrySkipIisCustomErrors in the error controller:

[HandleError]
public class ErrorController : Controller
{
  public ActionResult NotFound()
  {
    Response.TrySkipIisCustomErrors = true;
    Response.StatusCode = (int)HttpStatusCode.NotFound;
    return View("NotFound");
  }
  public ActionResult InternalServerError()
  {
    Response.TrySkipIisCustomErrors = true;
    Response.StatusCode = (int)HttpStatusCode.InternalServerError;
    return View("InternalServerError");
  }
}