【发布时间】:2018-07-18 09:03:28
【问题描述】:
作为参考,我使用的是 Visual Studio 2017 和 Windows 10。
我有一个 web api 和相应的带有用户帐户的 web 应用程序。当我尝试登录时,我遇到了一个错误,说没有 Access-Control-Allow-Origin 标头存在。我找到了指导我如何设置 CORS 的指南。这是我使用的指南。
在我的 WebApiConfig 文件中有这段代码
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
}
在我的 AccountController 文件中,我在顶部的 EnableCors 中添加了。
[EnableCors(origins: "*", headers: "*", methods: "*")]
[Authorize]
[RoutePrefix("api/Account")]
最后,在我的 Web.config 文件中,我添加了以下内容:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
这解决了我的登录问题,但是我的所有GETS 都不起作用。下面是一个 GET 函数的例子:
jQuery.support.cors = true;
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", 'http://localhost:60690/api/ProfilePicture?Username=' + username, false);
xmlhttp.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xmlhttp.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('accessToken'));
xmlhttp.send();
if (xmlhttp.status == 200) {
returnValue = jQuery.parseJSON(xmlhttp.responseText);
}
}
GET 抛出错误,提示“CORS 响应不允许使用多个 Access-Control-Allow-Origin 标头”。我看不到我在哪里有多个 Access-Control-Allow-Origin 标头。我应该去哪里看?
更新 1
发现了一些有趣的东西。我使用 Fiddler 来观察后台和 GET 函数中发生的所有事情,这会导致我在标题中看到这个错误:
所以“Access-Control-Allow-Origin: *”肯定显示了两次,但问题是为什么。我搜索了我所有的代码,我只声明了一次。如果我删除该行,它会破坏登录页面,所以我必须保留它。
【问题讨论】:
标签: c# asp.net-mvc asp.net-web-api xmlhttprequest cors