Sam Sam - 1 year ago 194
ASP.NET (C#) Question

Access-control-allow-origin with multiple domains

In my web.config I would like to specify more than one domain for the access-control-allow-origin directive. I don't want to use *. I've tried this syntax:

<add name="Access-Control-Allow-Origin" value="http://localhost:1506, http://localhost:1502" />

this one

<add name="Access-Control-Allow-Origin" value="http://localhost:1506 http://localhost:1502" />

this one

<add name="Access-Control-Allow-Origin" value="http://localhost:1506; http://localhost:1502" />

and this one

<add name="Access-Control-Allow-Origin" value="http://localhost:1506" />
<add name="Access-Control-Allow-Origin" value="http://localhost:1502" />

but none of them work.
What is the correct syntax ?

Answer Source

There can only be one Access-Control-Allow-Origin response header, and that header can only have one origin value. Therefore, in order to get this to work, you need to have some code that:

  1. Grabs the Origin request header.
  2. Checks if the origin value is one of the whitelisted values.
  3. If it is valid, sets the Access-Control-Allow-Origin header with that value.

I don't think there's any way to do this solely through the web.config.

if (ValidateRequest()) {
    Response.AddHeader("Access-Control-Allow-Origin", Request.UrlReferrer.GetLeftPart(UriPartial.Authority));

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

    Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download