我有一个在我的本地IIS上运行的ASP.NET Core API项目,以及一个在开发环境(http://localhost:53559)上运行的客户端网站。 API有一个受保护的资源,我想用授权标题调用它。
在我的ASP.NET API上,我使用了
启用了CORSservices.AddCors();
app.UseCors(builder => builder.AllowAnyOrigin());
我的ajax电话看起来像这样:
$.ajax({
type: "GET",
url: "http://localhost/MyApi/api/values",
async: true,
success: function (data) {
setJsonResult(data);
showResultPane("API request result");
},
error: function (obj, textStatus, errorThrown) {
setHtmlResult("Error returned by API: " + errorThrown);
showResultPane("Unauthorized request result");
},
beforeSend: function (request) {
if (currentToken) {
request.withCredentials = true;
request.setRequestHeader("Authorization", "Bearer " + currentToken);
}
}
});
如果我在请求中没有包含标题,那么我会按预期获得401响应。当我用Fiddler查看请求时,这就是我在请求中看到的内容:
GET http://localhost/MyApi/api/values HTTP/1.1
Host: localhost
Connection: keep-alive
Accept: */*
Origin: http://localhost:53559
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Referer: http://localhost:53559/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,he;q=0.6
但是当我添加我的授权标题时,我得到了一个204响应,这就是我对请求的反应(该过程不起作用,并且看起来并不像我期待的请求获取 - 不是GET调用,没有授权标题....):
OPTIONS http://localhost/MyApi/api/values HTTP/1.1
Host: localhost
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:53559
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Access-Control-Request-Headers: authorization
Accept: */*
Referer: http://localhost:53559/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,he;q=0.6
我正在使用IdentityServer来处理身份验证。
我在这里缺少什么?为什么我不能用请求发送标题?
答案 0 :(得分:0)
我已将以下内容添加到我的web.config中并且有效:
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Authorization" />