Access-Control-Allow-Origin标头具有多个值或预检jquery ajax到Web Api 2
我有一个在localhost上运行的asp.net Web表单应用程序:6414然后jquery ajax在localhost上调用Web Api服务 :11974
我收到错误
The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. Origin 'http://localhost:6414' is therefore not allowed access.
所以我梳理了google和stackoverflow ,发现了大量有冲突的 信息 。
1. Fix with web.config 2. Fix with jquery ajax call 3. Fix with CORS in web.api
我已经尝试了Cors启用和web.config以及各种技术 。
目前我想知道问题实际上是Web表单jquery代码作为发送者,但实际上响应头部意味着它来自web api服务…
我看看我的响应标题,我看到其中的两个
Access-Control-Allow-Origin:* ( repeated TWICE)
我尝试在Web Api Project中的web.config中注释掉这一行
然后我收到401错误:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:6414' is therefore not allowed access. The response had HTTP status code 401.
我在web.config中有这个代码
现在,如果我取消注释 Access-Control。 …在web.config中 ,然后注释掉 WebApiConfig .cs中的CORS代码
var cors = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(cors);
如果该代码被注释掉,那么我得到预检错误
XMLHttpRequest cannot load http://localhost:11974/PostCheckBox. Response for preflight has invalid HTTP status code 405
这似乎完全是疯了。
Jquery代码
function sendCheckboxes(id, out, yes, no) { //$(function () { //var storm = { id: 1902, StormOut: 1, StormYes: 1, StormNo: 1 }; var storm = { id: id, StormOut: out, StormYes: yes, StormNo: no }; //jQuery.support.cors = true; $.ajax({ type: "POST", data: JSON.stringify(storm), url: "http://localhost:11974/PostCheckBox", contentType: "application/json", //crossDomain: true, success: function (data) { console.log(data) }, error: function (x, y, z) { console.log(x + '\n' + y + '\n' + z); } }); //}); }
Web api方法
[Route("PostCheckBox")] public HttpResponseMessage PostCheckBox([FromBody] StormData storm) {.... }
如果我从同一个域调用此方法(现在在localhost上相同的端口)它工作正常
http://localhost:11974/checkbox.html
是什么赋予了…
你正在与web.config作斗争
注释掉你添加到web.config的所有垃圾!
我不使用它,我确定这是1个问题另一个是你需要注释掉
然后DO使用这些线
var cors = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(cors);
您总是可以添加安全性,身份validation和授权,并且Cors特定请求不是全局的,而是基于Class或Method,但是如果您在让事情发挥作用时遇到困难,那么这应该确实有效。
在startup.cs中启用cors
public void Configuration(IAppBuilder app) { HttpConfiguration config = new HttpConfiguration(); app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); ConfigureOAuth(app); WebApiConfig.Register(config); // Make sure this line is called before ConfigureAuth(app), // app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); app.UseWebApi(config); }