我有一个方案是从http向https发送ajax post请求(由于某些复杂的原因必须这样做),我需要为了cookie而传递凭据 .
我在服务器端使用Web Api,使用NuGet包Microsoft.AspNet.WebApi.Cors来启用Cors请求 .
客户端的代码:
$.ajax({
url: 'https://www.sitename.com/api/xxx',
type: 'post',
data: {
'': 1
},
headers: {
'__AntiXsrfTokenKey': 'whatevertokenhere'
},
xhrFields: {
withCredentials: true
},
dataType: 'json',
success: function (data) {
}
});
Web Api设置:
config.EnableCors();
控制器的EnableCors属性:
[EnableCors(origins: "http://www.sitename.com", headers: "*", methods: "*", SupportsCredentials = true)]
public class XXXController : ApiController
预检请求 Headers :
Access-Control-Request-Headers: accept, __AntiXsrfTokenKey, content-type
Access-Control-Request-Method: POST
Origin: http://www.sitename.com
响应头:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: __AntiXsrfTokenKey,content-type
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS
Access-Control-Allow-Origin: *
问题很明显是Access-Control-Allow-Origin标头返回一个通配符*,而不是我在控制器'http://www.sitename.com'的属性中指定的请求源 . 所以我最终得到了错误:
A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://www.sitename.com' is therefore not allowed access.
有没有人知道为什么这种行为以及如何在EnableCors属性中正确设置Access-Control-Allow-Origin域?
1 回答
好的,终于在system.webServer中的web.config中找到了这个