How to override IIS default error messages?

Today I was working on retrieving status codes in ASP.NET MVC 4 application. I needed correct status codes for my ajax requests to show correct error message (in case of an error, of course). The problem was that IIS was redirecting when status code was added to response. In case of status code 401 it redirected to basic login, in case of status code 403 it redirected to IIS generic error page and so on. If you are working with .NET version 4.5 there exists very simple solution:

Response.TrySkipIisCustomErrors = true;

But not with .NET version 4.0. 🙂 In that case you have to add few lines into your Web.config file inside of system.webServer node:

<httpErrors existingResponse="PassThrough">
  <remove statusCode="403"/>
  <error statusCode="403" responseMode="ExecuteURL" path="~/StatusCode/Unauthorized"/>
  <remove statusCode="401"/>
  <error statusCode="401" responseMode="ExecuteURL" path="~/StatusCode/Forbidden"/>
  <remove statusCode="404"/>
  <error statusCode="404" responseMode="ExecuteURL" path="~/StatusCode/NotFound"/>
</httpErrors>

With attribute value “PassThrough” (attribute existingResponse) you tell IIS to leave response untouched if an existing response exists. You can check other attribute options here. Value of attribute path inside of node error represents the path to the response (for example: “~/ControllerName/ActionName”). That way you can override IIS’ default error responses with your custom error responses.

Leave a Comment.