c# – WebApi CORs – 请求错误时出现Access-Control-Allow-Orig
问题背景:
这似乎是一个普遍的问题,而且我已经犯了一个错误. 我有一个目前在Azure中托管的标准WebApi和一个调用AngularJS应用程序,该应用程序在所述WebApi上调用终点. 调用WebApi的AngularJS应用程序URL是: http://siteang.azurewebsites.net WebApi地址是: https://site.azurewebsites.net 我想确保只有我在http://siteang.azurewebsites.net上的应用程序才能访问https://site.azurewebsites.net上的WebApi 问题: 我在AngularJS应用程序的提交表单上收到以下错误给WebApi服务. XMLHttpRequest cannot load https://site.azurewebsites.net/api/ShoppingComparison/GetC…itemIndex=Baby&itemtosearch=baby&lowToHigh=false&maxPrice=50000&minPrice=0. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://siteang.azurewebsites.net' is therefore not allowed access. The response had HTTP status code 500. 代码: 以下是对WebApi服务的$http请求. 请注意,调用的header属性已使用AngularJS站点的地址设置. loadSearchList: function (itemToSearch,itemIndex,countryCode) { self.itemToSearch = itemToSearch; self.itemCatagory = itemIndex; self.country = countryCode; self.searchList = []; $http({ method: 'GET',url: 'https://site.azurewebsites.net/api/ShoppingComparison/GetComparisons',params: { itemtosearch: itemToSearch,itemIndex: itemIndex,countryCode: countryCode,maxPrice: '50000',minPrice: '0',highToLow: true,lowToHigh: false,amazonEbay: true,amazonOnly: false,ebayOnly: false },headers: { 'Content-Type': 'text/plain; charset=UTF-8','Access-Control-Allow-Origin': 'http://siteang.azurewebsites.net','Access-Control-Allow-Methods': 'POST,GET,OPTIONS,PUT,DELETE' } }).success(function (data) { //Success Handler. }).error(function (data) { //Error Handler. }); } 以下是AngularJS应用程序正在调用的WebApi控制器.请注意,标头已设置为接受正在进行呼叫的http://siteang.azurewebsites.net网站: [System.Web.Http.HttpGet] [EnableCors(origins: "http://siteang.azurewebsites.net",headers: "*",methods: "*")] public ViewItemModel GetComparisons([FromUri] ComparisonRequestModel comparisonModel) { return _callAndSearchApis.SearchApis(comparisonModel); } 任何帮助确定WebApi控制器拒绝此请求的原因将非常感激. 解决方法
浏览器会自动为跨源请求强加CORS请求标头.没有办法改变它们.事实上,如果客户端可以设置CORS允许头,CORS将毫无意义.
您看到的错误是您的服务器在预检请求期间未在响应中包含所需的Access-Control-Allow- *标头.当客户端执行除简单GET请求之外的操作时,执行预检请求(OPTIONS),包括添加自定义请求标头(您的允许标头是哪个). 公平地说,错误可能无助于您的混淆(“…不存在于请求的资源上”). 我建议从请求中删除CORS标头并再次尝试.如果仍然失败,请使用像Fiddler这样的HTTP代理捕获请求,并使用预检请求和响应中的CORS标头更新您的问题. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |