CustomErrors does not work when setting redirectMode="ResponseRewrite"

The only way that worked perfectly for me is to turn off custom errors and replace iis's error pages via web.config. It sends the correct status code with the response and has the benefit of not going through the mvc.

here's the code

  1. Turn off custom errors

    <customErrors mode="Off" />
    
  2. Replace error pages

    <httpErrors errorMode="Custom" existingResponse="Replace">
      <remove statusCode="404" subStatusCode="-1" />
      <remove statusCode="500" subStatusCode="-1" />
      <error statusCode="404" path="Error404.html" responseMode="File" />
      <error statusCode="500" path="Error.html" responseMode="File" />
    </httpErrors>
    

Note. Use responsemode="file" if the url is a direct link to a file

info : http://tipila.com/tips/use-custom-error-pages-aspnet-mvc


It is important to note for anyone trying to do this in an MVC application that ResponseRewrite uses Server.Transfer behind the scenes. Therefore, the defaultRedirect must correspond to a legitimate file on the file system. Apparently, Server.Transfer is not compatible with MVC routes, therefore, if your error page is served by a controller action, Server.Transfer is going to look for /Error/Whatever, not find it on the file system, and return a generic 404 error page!


What's happening is IIS is seing the error status code and presenting it's own error page instead of yours. To solve you need to set this in the code behind page of your error page to prevent IIS from doing this:

Response.TrySkipIisCustomErrors = true;

This will only work in IIS7 or above, for earlier versions of IIS you'll need to play with the error page settings.