vitaly-t vitaly-t - 1 year ago 135
ASP.NET (C#) Question

Accessing pre-configured IIS response headers from a web service

How to access IIS-configured response headers from a Web API 2 service?

In my IIS configuration there is a pre-configured response header

, which I need to check to figure out which environment settings to use.

When I check headers in my current response via
, I'm only seeing
, and nothing else.

Answer Source

I don't think you should dependent on response headers as they are added to response by IIS at a very later stage in the pipeline and the control is already out of WEB API.

If you have to do this you can go with URL Rewrite + Server Variables. Install URL Rewrite and add a rule in your web.config under system.webServer as below

        <rule name="GetEnvironmentInfo">
            <match url=".*" />
                <set name="Environment" value="Dev" />
            <action type="Rewrite" url="{R:0}" />

Also you can add this rule from IIS UI. Now depending upon webAPI configuration you can fetch server variables using below code

string output = string.Empty;
if (Request.Properties.ContainsKey("MS_HttpContext"))
    output = ((System.Web.HttpContextWrapper)Request.Properties["MS_HttpContext"]).Request.ServerVariables["Environment"];
else if (Request.Properties.ContainsKey("MS_OwinContext"))
    var httpContextWrapper = ((OwinContext)Request.Properties["MS_OwinContext"]).Environment["System.Web.HttpContextBase"] as HttpContextWrapper;
    output = httpContextWrapper.Request.ServerVariables["Environment"];

The above XML can be generated from IIS GUI at server level

1.Install URL Rewrite.

2.Open IIS Manger (Windows Run -> Inetmgr)

3.Select Server in left menu

4.In the central pane double click URL Rewrite. In the Actions pane on the right hand side click Add Rule

5.Set values as below

enter image description here

and the save.

This will add same XML but now at the server level i.e. in C:\Windows\System32\inetsrv\Config\applicationHost.config file

            <rule name="GetEnInfo">
                <match url=".*" />
                <action type="Rewrite" url="{R:0}" />
                    <set name="Environment" value="dev" />

Regarding fetching response headers from IIS there could be a way but I wouldn't recommend it due to the reason mentioned in the beginning of the answer.

Hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download