我有一个场景可以将ajax post请求从http发送到https(出于某些复杂的原因必须这样做),我需要为了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
预检请求标题:
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域?
答案 0 :(得分:0)
好的,终于在system.webServer
中的web.config中找到了这个<rewrite>
<outboundRules>
<rule name="Set Access-Control-Allow-Origin header">
<match serverVariable="RESPONSE_Access-Control-Allow-Origin" pattern="(.*)" />
<action type="Rewrite" value="*" />
</rule>
</outboundRules>
</rewrite>