How to prevent IIS7 for handling HTTP status code 401?

前端 未结 2 1388
夕颜
夕颜 2020-12-15 07:52

I\'m working my ASP.NET MVC 2 project. I create exception filter for catching unauthorized access exception that occur when user does not has permission to view some action.

相关标签:
2条回答
  • 2020-12-15 08:16

    I just found easy solution for this problem. I just add new setting in to web.config file like the following code. Everything works fine on my deployment website.

      <?xml version="1.0" encoding="utf-8"?>
      <configuration> 
        <system.webServer>
          <httpErrors errorMode="Custom" existingResponse="PassThrough">
              <remove statusCode="502" subStatusCode="-1" />
              <remove statusCode="501" subStatusCode="-1" />
              <remove statusCode="500" subStatusCode="-1" />
              <remove statusCode="412" subStatusCode="-1" />
              <remove statusCode="406" subStatusCode="-1" />
              <remove statusCode="405" subStatusCode="-1" />
              <remove statusCode="404" subStatusCode="-1" />
              <remove statusCode="403" subStatusCode="-1" />
              <remove statusCode="401" subStatusCode="-1" />
          </httpErrors>
        </system.webServer>
      </configuration>
    

    So I can create custom error page both in plain text and JSON response too.

    For more information: HttpErrorsSection Class

    PS. But I cannot found existingResponse attribute in Error Pages feature of IIS manager.

    0 讨论(0)
  • 2020-12-15 08:23

    You can pass through IIS7 default error messages in two ways

    One is to set response.TrySkipIisCustomErrors to be true

    response.TrySkipIisCustomErrors = true;
    response.Status = response.Status;
    

    For some reason, TrySkipIisCustomErrors is not honoured if you don't set response.Status.

    The other is to set existingResponse to "PassThrough" in web.config

    <configuration>
      <system.webServer>
        <httpErrors existingResponse="PassThrough" />
      </system.webServer>
    </configuration>
    

    But this will ignore all set IIS custom error pages.

    0 讨论(0)
提交回复
热议问题