0

We have a definition in web.config to set Access-Control-Allow-Origin header for all requests to one predefined server. like this:

<customHeaders>
    <add name="Access-Control-Allow-Origin"value="http://constantServer.com" />
    <add name="Accept-Bytes" value="none" />
</customHeaders>

there are some cases we need to allow access to different server to a specific resource. we check the origin and set the Access-Control-Allow-Origin by code, like this:

Response.AddHeader("Access-Control-Allow-Origin", origin);
Response.AddHeader("Access-Control-Allow-Credentials", "true");

The problem is that the browser get multiple values for the Access-Control and its not allowed it.

We want to remove by code the header that was defined in the web.config in cases that we need to allow it for different origin.

I tried to remove it at the global.asax in the Application_PreSendRequestHeaders event, but i didnt find this header there.(its seems that this header is being added after this event)

Thanks

amichai
  • 718
  • 9
  • 19
  • 1
    you could implement a custom `HttpModule` and change the header value to whatever you want. https://msdn.microsoft.com/en-us/library/system.web.httpapplication.postauthenticaterequest(v=vs.110).aspx – Amit Kumar Ghosh Jan 08 '16 at 07:53

1 Answers1

1

See this answer for more details on IHttpModule solution on how to change a header value. It was about the Server default header added by IIS, which I believe to be the harder case to handle.

This question provides a lot of other options in its answers, including installing and using URL Rewrite (direct link to corresponding answer).

You may by example change your code to only add the Access-Control-Allow-Credentials, then write a URL Rewrite rule for changing Access-Control-Allow-Originto origin.

<system.webServer>
    ...
    <rewrite>
        <outboundRules>
            <rule name="handleCredentialCors" preCondition="credential">
                <match serverVariable="Access-Control-Allow-Origin" pattern=".*" />
                <action type="Rewrite" value="origin" />
            </rule>
            <preConditions>
                <preCondition name="credential">
                    <add input="{RESPONSE_Access_Control_Allow_Credentials}" pattern="true" />
                </preCondition>
            </preConditions>
        </outboundRules>
    </rewrite>
    ...
</system.webServer>

(Untested)

My bad, I have overlooked origin was a local variable, not a literal string.

Well, if you can infer that origin value from server variables (which in URL rewrite include request headers), URL Rewrite may still get the job done. It is able of extracting values then reusing them in the rewritten value. But the rule could be a bit more complex to write.

Community
  • 1
  • 1
Frédéric
  • 9,364
  • 3
  • 62
  • 112