Custom http status code for specific resource in I

2019-06-28 07:00发布

问题:

I have a web site with a single 'app_offline.htm' file. How can i configure IIS to return it with specific status code (say, 209) instead of default one (200)?

回答1:

An alternative to using the 'app_offline.htm' feature of ASP.Net could be to use the IIS URL Rewrite Module, it has a huge bag of tricks and setting custom response codes is one of them.

If the content of the page is not important, only the response code, then with that module you can configure a rule that will return a blank response with a 209 code to any request as long as the rule is enabled.

That will materialise in your web.config as something like this:

<configuration>
    <system.webServer>       
        <rewrite>
            <rules>
                <rule name="app_offline" stopProcessing="true">
                    <match url=".*" />
                    <action type="CustomResponse" statusCode="209" statusReason="System unavailable" statusDescription="The site is currently down for maintenance, or something." />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>


回答2:

Since IIS has special handling for a file named 'app_offline.htm' in the root of your web site, this suggestion may not work, unless you rename the file. But, here it is anyway...

You can use an HttpHandler for this. In your web.config, add something like this:

<add name="app_offline_GET" path="app_offline.htm" verb="GET" type="namespace.classname,dllname" />

Obviously, substitute the proper info in the 'type' attribute.

In the HttpHandler, do something like this:

public void ProcessRequest(HttpContext context) {
  context.Response.WriteFile("app_offline.htm");
  context.Response.StatusCode = 209;        
  context.Response.StatusDescription = "whatever";
}


回答3:

To show specific content based on status code, you can let the response set the status code and map the content to show based on the code in the httpErrors section. See example in this post https://serverfault.com/questions/483145/how-to-add-a-site-wide-downtime-error-message-in-iis-with-a-custom-503-error-co

For the benefit of preservation, I will replicate the example below:

<system.webServer>
    ...
    <rewrite>
        <rules>
            <rule name="SiteDown" stopProcessing="true">
                <match url=".*" />
                <action type="CustomResponse" statusCode="503" statusReason="Down for maintenance" statusDescription="will be back up soon" />
            </rule>
        </rules>
    </rewrite>

      <httpErrors existingResponse="Auto" errorMode="Custom" defaultResponseMode="File">
             <remove statusCode="503" subStatusCode="-1" />
             <error statusCode="503" path="503.html" />
      </httpErrors>
</system.webServer>


标签: http iis iis-7