与 CORS 作战。我有一个网站正在向我在 C# 中构建的 WEB API 发出简单的 XmlHttpRequest。
var xhr = new XMLHttpRequest();
xhr.open("GET","https://server/controller/method", true);
xhr.send();
在我的 web.config 中,我完成了以下操作:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
我还尝试安装 Nuget 包并在我的 WebApiConfig.cs 中执行以下操作
var cors = new EnableCorsAttribute(
origins: "*",
headers: "*",
methods: "*");
config.EnableCors(cors);
尽管做出了这些努力,CORS 仍然无法正常工作。在 FireFox 控制台中,我收到以下错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://server. This can be fixed by moving the resource to the same domain or enabling CORS.
IE 也只是失败并且没有给出错误。
根据我所阅读的所有内容,这些解决方案中的一个应该有效,但它们却没有。是否需要在客户端 JavaScript 中启用/更改某些内容?当您在 localhost:PortNumber 上的 Visual Studio IIS Express 中运行 CORS 时,它是否不起作用?我错过了什么?
最佳答案
在您的客户端 JavaScript 代码中,您可以尝试添加:
xhr.withCredentials = true;
如 Firefox 'Cross-Origin Request Blocked' despite headers 中所示:
otherwise Firefox failed to use the client cert when making the request
但是,如果您对客户端代码进行了更改,则还必须更改服务器端代码,以便 Access-Control-Allow-Origin
的值不是 *
。有几种方法可以做到这一点......
在 IIS 配置中,您可以使用 URL Rewrite Module通过将以下内容添加到 %SystemDrive%\inetpub\wwwroot\
中的 Web.config
或 ApplicationHost.config
文件。
<configuration>
<system.webServer>
<rewrite>
<outboundRules>
<rule name="Make Access-Control-Allow-Origin echo Origin">
<match serverVariable="RESPONSE_Access-Control-Allow-Origin"
pattern=".+" negate="true" />
<action type="Rewrite" value="{HTTP_ORIGIN}" />
</rule>
</outboundRules>
</rewrite>
</system.webServer>
</configuration>
如果上述方法不起作用,那么您可以在 CORS in IIS issue with credentials and wildcard in Access-Control-Allow-Origin 尝试答案中的版本.
另一种方式:in the global.asax
or other code for your service, add something like this :
if (ValidateRequest()) {
Response.Headers.Remove("Access-Control-Allow-Origin");
Response.AddHeader("Access-Control-Allow-Origin", Request.Headers["origin"]);
Response.Headers.Remove("Access-Control-Allow-Credentials");
Response.AddHeader("Access-Control-Allow-Credentials", "true");
Response.Headers.Remove("Access-Control-Allow-Methods");
Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
}
...最重要的部分是:
Response.AddHeader("Access-Control-Allow-Origin", Request.Headers["origin"]);
如果这些都不起作用,请尝试 an approach using Microsoft.AspNet.WebApi.Cors
.
关于javascript - C# WEB API CORS 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42279081/