允许CORS提供MVC中的静态内容
我有一个运行在www.domain.com(始终为www)上的ASP.NET MVC应用程序。我的静态域在static.domain.com上运行。
I have an ASP.NET MVC application which runs on www.domain.com (always www). My static domain runs on static.domain.com.
现在,我在Web.Config中将Access-Control-Allow-Origin设置为 *:
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"/>
允许任何协议(这是我理想中想要的,或者如果我可以添加两个规则,一个代表http,一个代表https)。这没用,所以我也尝试了http://协议。
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"/>
这也不起作用。
我在stackoverflow上阅读了类似的主题,但我发现的所有内容都建议像在上一个示例 http://static.domain.com ...
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!
谢谢!
迈克
答案类似于其他帖子的答案。仅通过web.config根本不可能。需要在Global.asax.cs文件中以编程方式进行设置。
The answer to this is similar to other posts answers. It simply is not possible through only the web.config. It needs to be set programmatically in the Global.asax.cs file.
这是通过在Global.asax的Application_EndRequest()方法中添加一些代码行来完成的。 CS文件。我将代码提取到一个方法中,但是您可以根据需要将代码直接放入其中。
This is done by adding some lines of code in the Application_EndRequest() method in Global.asax.cs file. I extracted the code into a method, but you can put the code straight inside if you wish.
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");
}
这很不错,因为 Request.Headers [ Host]
无法获取协议,我们可以检查字符串数组是否匹配,将Access-Control-Allow-Origin设置为允许所有内容,否则将其删除。因此,在某种程度上,我们是动态设置密钥的。
This works great, since the Request.Headers["Host"]
does not get the protocol, we can just check if there is any match with our string array, the we set the Access-Control-Allow-Origin to allow everything, otherwise we remove it. So in a way, we are dynamically setting the key.
这需要在Global.asax.cs中,因为它需要根据每个请求进行(因为我们需要也可以将其用于所有资源文件)。
This needs to be in the Global.asax.cs since it needs to be on EVERY request (since we need to use this for all resource files as well).