作为参考,我使用的是Visual Studio 2017和Windows 10。
我有一个MVC webapi项目,它使用Visual Studio提供的模板设计,其中的帐户存储在SQL数据库中。我有另一个项目,这是网站本身的用户登录。我正在尝试在VS中调试,但每当在初始登录之外发出GET请求时,都会遇到一条“访问被拒绝”错误消息。我已经在webapi上启用了CORS,但似乎没有什么不同。
下面是我如何启用CORS的。
在WebAPIConfig文件中,我有以下内容:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
然后在网络上。配置文件我有:
<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>
这是打电话的网站上的代码:
function getProfilePicture(username){
var returnValue = [];
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);
}
}
return returnValue;
}
错误消息显示“SCRIPT7002:XMLHttpRequest:Network error 0x80070005,访问被拒绝。”
我没有正确启用CORS吗?
使现代化
我下载了《邮差》,试图找出问题所在。事实上,我可以与邮递员无误地拨打GET电话。它正在返回数据和所有内容。我注意到的一件事是,授权标头看起来并没有实际发送。Fiddler中的数据中缺少它。