use*_*057 6 c# asp.net-web-api angularjs
问题背景:
这似乎是一个普遍的问题,而且我已经犯了一个错误.
我有一个目前在Azure中托管的标准WebApi和一个调用AngularJS应用程序,该应用程序在所述WebApi上调用终点.
调用WebApi的AngularJS应用程序URL是:
http://siteang.azurewebsites.net
Run Code Online (Sandbox Code Playgroud)
WebApi地址是:
https://site.azurewebsites.net
Run Code Online (Sandbox Code Playgroud)
我想确保只有我的应用程序http://siteang.azurewebsites.net才能访问WebApihttps://site.azurewebsites.net
问题:
我在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.
Run Code Online (Sandbox Code Playgroud)
代码:
以下是对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.
});
}
Run Code Online (Sandbox Code Playgroud)
以下是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);
}
Run Code Online (Sandbox Code Playgroud)
任何帮助确定WebApi控制器拒绝此请求的原因将非常感激.
浏览器会自动为跨源请求强加 CORS请求标头.没有办法改变它们.事实上,如果客户端可以设置CORS允许头,CORS将毫无意义.
您看到的错误是您的服务器在预检请求期间未Access-Control-Allow-*在响应中包含所需的 标头.当客户端执行除简单GET请求之外的操作时,执行预检请求(OPTIONS),包括添加自定义请求标头(您的允许标头是哪个).
公平地说,错误可能无助于您的混淆("...不存在于请求的资源上").
我建议从请求中删除CORS标头并再次尝试.如果仍然失败,请使用像Fiddler这样的HTTP代理捕获请求,并使用预检请求和响应中的CORS标头更新您的问题.
| 归档时间: |
|
| 查看次数: |
6103 次 |
| 最近记录: |