我有一个已启用CORS的Web API。我已经包含在代码中:
WebApiConfig.cs
config.EnableCors(new EnableCorsAttribute("*", headers: "*", methods: "*"));
MyController.cs
[EnableCors(origins: "*", headers: "*", methods: "*")]
我正在使用NuGet包中的Microsoft.AspNet.WebApi.Cors,以使用该库来启用CORS。但是,当我尝试使用JQuery在前端调用API时,仍然出现此错误:
GET http://localhost:52259/api/coreactivities/getAllTeams 401 (Unauthorized)
Access to XMLHttpRequest at 'http://localhost:52259/api/coreactivities/getAllTeams' from origin 'http://localhost:52349' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我也尝试将这一行代码包含在API的Web.config中,但仍然出现401未经授权的错误。在我的API中,我没有该身份或没有设置任何身份验证。
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD, OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true"/>
<add name="Access-Control-Allow-Headers" value="X-Requested-With, origin, content-type, accept" />
</customHeaders>
</httpProtocol>
</system.webServer>
我不知道代码中有什么错误或遗漏以允许跨域。
有什么建议吗?
添加了我的JQuery调用:
function displayTeam() {
var url = 'http://localhost:52259/api/coreactivities/getAllTeams';
$.get(url, function (result) {
console.log(result);
}).done(function (data) {
console.log(data);
})
.fail(function (error) {
console.log(error);
});
}