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

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.