asp.net - Allow CORS for static content in MVC -


i have asp.net mvc application runs on www.domain.com (always www). static domain runs on static.domain.com.

right setting access-control-allow-origin "*" in web.config:

<add name="access-control-allow-origin" value="*"/> 

however, not practice. tried adding following:

<add name="access-control-allow-origin" value="//static.domain.com"/> 

to allow protocols (which ideally want, or if add 2 rules, 1 http , 1 https). didn't work, tried http:// protocol.

<add name="access-control-allow-origin" value="http://static.domain.com"/> 

which did not work either.

i've read through similar threads/questions here @ stackoverflow, find suggests add domain did in last example "http://static.domain.com"...

i must doing wrong, can't seem is. hope can me!

thanks in advance!

mike

the answer similar other posts answers. not possible through web.config. needs set programmatically in global.asax.cs file.

this done adding lines of code in application_endrequest() method in global.asax.cs file. extracted code method, can put code straight inside if wish.

string[] domains = {"static.domain.com", "domain.com"}; // config  if (request != null || request.headers != null || response != null || response.headers != null) {       string host = request.headers["host"]; // doesn't care protocol    if (domains.where(domain => domain == host).count() > 0)     response.headers.add("access-control-allow-origin", "*");   else     response.headers.remove("access-control-allow-origin"); } 

this works great, since request.headers["host"] not protocol, can check if there match our string array, set access-control-allow-origin allow everything, otherwise remove it. in way, dynamically setting key.

this needs in global.asax.cs since needs on every request (since need use resource files well).


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -