在我的 API 中,我有以下代码:
public class CustomOAuthProvider : OAuthAuthorizationServerProvider
{
public override Task MatchEndpoint(OAuthMatchEndpointContext context)
{
if (context.OwinContext.Request.Method == "OPTIONS" && context.IsTokenEndpoint)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "POST" });
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Headers",
new[] {
"access-control-allow-origin",
"accept",
"x-api-applicationid",
"content-type",
"authorization"
});
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
context.OwinContext.Response.StatusCode = (int)HttpStatusCode.OK;
context.RequestCompleted();
return Task.FromResult<object>(null);
}
return base.MatchEndpoint(context);
}
// ... even more code, but not relevant
}
当我从 Chrome 连接到这个 API 时,一切正常。当我从同一台计算机连接到同一 API,但仅从不同的浏览器 Internet Explorer 11 连接时,出现以下错误:
SEC7123: Request header x-api-applicationid was not present in the Access-Control-Allow-Headers list.
我调试了代码,我看到标题已添加到响应中。即使 IE 显示标题:
IE 期望什么?
更新
如果我改变标题的顺序
new[] {
"access-control-allow-origin",
"accept",
"x-api-applicationid",
"content-type",
"authorization"
}
到:
new[] {
"content-type",
"accept",
"access-control-allow-origin",
"x-api-applicationid",
"authorization"
}
错误信息更改为:
SEC7123: Request header access-control-allow-origin was not present in the Access-Control-Allow-Headers list.
所以它总是在第三个标题上给出错误。
最佳答案
确保它不像 AJAX 中内容类型 header 的拼写错误那么简单。我通过带有 application/x-www-form-urlencoded
的 OPTIONS 预检得到了这个内容类型,不需要预检,但我有content-type: application/x-www-form-urlencoded
代替application/x-www-form-urlencoded
作为我的 contentType
选项。
错误的:
$.ajax({
url: 'http://www.example.com/api/Account/Token',
contentType: 'content-type: application/x-www-form-urlencoded',
method: 'POST',
data: {
grant_type: "password",
username: $('#username').val(),
password: $('#password').val()
},
});
对:
$.ajax({
url: 'http://www.example.com/api/Account/Token',
contentType: 'application/x-www-form-urlencoded',
method: 'POST',
data: {
grant_type: "password",
username: $('#username').val(),
password: $('#password').val()
},
});
关于internet-explorer - 请求头不在 Access-Control-Allow-Headers 列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27168061/