【发布时间】:2017-01-28 21:19:52
【问题描述】:
问题背景:
这似乎是一个常见的问题,我已经犯了一个错误。
我有一个当前托管在 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:caniuse.com/cors
-
你打电话给
config.EnableCors();了吗? -
您可以尝试的另一件事是删除
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' },这样浏览器就不需要发送预检请求 -
@KhanhTO 感谢您的回复。我按照你说的做了并删除了 JSON 标头,这确实意味着我只能从一个特定的 Web 应用程序请求。但是,如果我将 WebApi URL 放入 POSTMAN 中,它仍然允许访问 API 并返回结果,这是为什么呢?
标签: c# angularjs asp.net-web-api