Allow CORS for static content in MVC

时间:2015-06-26 10:28:45

标签: asp.net asp.net-mvc cors

I have an ASP.NET MVC application which runs on www.domain.com (always www). My static domain runs on static.domain.com.

Right now I am setting Access-Control-Allow-Origin to "*" in Web.Config:

<add name="Access-Control-Allow-Origin" value="*"/>

However, obviously this is not good practice. So I tried adding the following:

<add name="Access-Control-Allow-Origin" value="//static.domain.com"/>

To allow any protocols (which is what I ideally want, or if I could add two rules, one for http and one for https). This didn't work, so I also tried with 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 at stackoverflow, but everything i find suggests to add the domain as i did in the last example "http://static.domain.com"...

I must be doing something wrong, but I can't seem to get what that is. Hope you can help me!

Thanks in advance!

Mike

1 个答案:

答案 0 :(得分:1)

这个答案类似于其他帖子答案。仅仅通过web.config是不可能的。它需要在Global.asax.cs文件中以编程方式设置。

这是通过在Global.asax.cs文件中的Application_EndRequest()方法中添加一些代码行来完成的。我将代码解压缩到一个方法中,但如果您愿意,可以将代码直接放在内部。

declare(ticks=…)

这很好用,因为string[] domains = {"static.domain.com", "domain.com"}; // Personally I get this from a config if (Request != null || Request.Headers != null || Response != null || Response.Headers != null) { string host = Request.Headers["Host"]; // This doesn't care about protocol if (domains.Where(domain => domain == host).Count() > 0) Response.Headers.Add("Access-Control-Allow-Origin", "*"); else Response.Headers.Remove("Access-Control-Allow-Origin"); } 没有得到协议,我们可以检查是否与我们的字符串数组匹配,我们设置Access-Control-Allow-Origin以允许所有内容,否则我们删除它。所以在某种程度上,我们是动态设置密钥。

这需要在Global.asax.cs中,因为它需要在每个请求上(因为我们也需要将它用于所有资源文件)。