作为参考,我使用的是 Visual Studio 2017 和 Windows 10。
我有一个 Web api 和带有用户帐户的相应 Web 应用程序。当我尝试登录时遇到一个错误,指出不存在 Access-Control-Allow-Origin 标头。我找到了一个指南,引导我了解如何设置 CORS。这是我使用的指南。
https://social.technet.microsoft.com/wiki/contents/articles/33771.fix-to-no-access-control-allow-origin-header-is-present-or-working-with-cross-origin-请求在 asp-net-web-api.aspx https://social.technet.microsoft.com/wiki/contents/articles/33771.fix-to-no-access-control-allow-origin-header-is-present-or-working-with-cross-origin-request-in-asp-net-web-api.aspx
在我的 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 标头。我应该去哪里寻找?
Update 1
发现了一些有趣的事情。我使用 Fiddler 来观察后台发生的所有事情以及导致错误的 GET 函数,我在标题中看到了这个:
因此,“Access-Control-Allow-Origin: *”肯定显示了两次,但问题是为什么。我搜索了所有代码,但只声明了一次。如果我删除该行,它会破坏登录页面,因此我必须将其保留。