我无法让CORS与WebAPI协同工作。我正在实现ICorsPolicyProvider:
public class CustomCorsPolicy : Attribute, ICorsPolicyProvider
{
private CorsPolicy _policy;
public CustomCorsPolicy()
{
_policy = new CorsPolicy
{
AllowAnyMethod = true,
AllowAnyHeader = true
};
_policy.Origins.Add("http://****");
_policy.Origins.Add("http://localhost:8080");
}
public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return Task.FromResult(_policy);
}
}
这适用于GET,PUT和DELETE方法,但对于POST方法,预检请求不会在响应中呈现Access-Control-Allow-标头。
这是PUT的预检响应(有效):
Access-Control-Allow-Headers:content-type
Access-Control-Allow-Methods:PUT
Access-Control-Allow-Origin:http://localhost:8080
Cache-Control:no-cache
Content-Length:0
Date:Fri, 30 Jan 2015 21:37:42 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/8.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpccmVwb1xmb3NfYWxsXHNyY1xFbGxpb3R0LkZyb250T2ZmaWNlLkRhdGFNYW5hZ2VtZW50XGFwaVxmaXhpbmdDb25maWd1cmF0aW9uc1wwRUg1Q185OC43NTAsOVw=?=
这是POST的预检响应(不起作用):
Allow:OPTIONS, TRACE, GET, HEAD, POST
Content-Length:0
Date:Fri, 30 Jan 2015 21:56:22 GMT
Public:OPTIONS, TRACE, GET, HEAD, POST
Server:Microsoft-IIS/8.0
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpccmVwb1xmb3NfYWxsXHNyY1xFbGxpb3R0LkZyb250T2ZmaWNlLkRhdGFNYW5hZ2VtZW50XGFwaVxmaXhpbmdzXA==?=
答案 0 :(得分:0)
我使用这个解决方案解决了这个问题:
https://stackoverflow.com/a/14631068/85733
我使用的是CORS nuget,我认为它无法正常使用。不要浪费你的时间。这适用于预检:
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}