[英]ASP.Net WEB API Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response
I wrote my WEBAPI code to get some data to authinticated users, I faced multible issues and it is solved.我编写了我的 WEBAPI 代码来向经过身份验证的用户获取一些数据,我遇到了多种问题并且解决了。 but now I face issue when I tried to get list of data for authinticated user chrome give me this error
但是现在当我尝试获取经过身份验证的用户的数据列表时遇到问题 chrome 给我这个错误
XMLHttpRequest cannot load http://192.168.10.95/KS.API.Client/api/Data . XMLHttpRequest 无法加载http://192.168.10.95/KS.API.Client/api/Data 。 Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
预检响应中的 Access-Control-Allow-Headers 不允许请求头字段授权。
aAnd this is who I called WebApi methor from pure html page a 这就是我从纯 html 页面调用 WebApi methor 的人
$.ajax({
url: domain + '/api/Data',
type: 'GET',
beforeSend: function (xhr) {
debugger;
xhr.setRequestHeader("Authorization", " Bearer " + sessionStorage.getItem("Token"));
},
success: function (response) {
$.each(response, function () {
$('#myTable').append(
'<tr><td>'
+ this.username
+ '</td><td>'
+ this.password +
'</td></tr>'
);
});
// response
},
error: function (err) {
alert(err.responseText);
}
});
Please lep me请放过我
In your WebAPI, you need to install package Microsoft.Owin.Cors.在您的 WebAPI 中,您需要安装包 Microsoft.Owin.Cors。 Open Nuget Package Console, type this
打开 Nuget 包控制台,输入这个
Install-Package Microsoft.Owin.Cors
After install adding reference, you need to go to Startup.cs add this line app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
安装添加引用后,需要到Startup.cs添加这一行
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
into your Configuration function It will looks something like this进入您的配置功能它看起来像这样
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
Add the following to your web.config file of your Web API in order to enable access:将以下内容添加到 Web API 的 web.config 文件中以启用访问:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
</customHeaders>
</httpProtocol>
This should be placed inside system.webServer node of your web.config.这应该放在你的 web.config 的 system.webServer 节点中。
Please read official documentation in order to properly use and control access from outside using CORS请阅读官方文档以正确使用和控制从外部使用 CORS 的访问
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.