【发布时间】:2017-02-15 13:27:15
【问题描述】:
在服务器端,我有一个 C# web api,包括一个在类级别上属性如下的控制器:
[EnableCors(origins: "http://localhost:51664,http://localhost,...", headers: "*", methods: "*")]
我可以进行 ajax 调用,例如形成本地主机就好了。
现在我从 AngularJS 开始,http.get-method 失败并显示以下消息:
XMLHttpRequest 无法加载 http://localhost:8081/DividendsManager.Web.Api/api/securities/GetSecurities?yearsDividendsDontDecrease=40。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问 Origin 'null'。
这是我的 AngularJS 代码:
<script>
var myApp = angular.module('myApp', []);
myApp.controller("myController", function($scope, $http) {
var onSuccess = function(data, status, headers, config) {
$scope.data = data;
};
var onError = function(data, status, headers, config) {
$scope.error = status;
}
var promise = $http.get("http://localhost:8081/DividendsManager.Web.Api/api/securities/GetSecurities?yearsDividendsDontDecrease=40");
promise.success(onSuccess);
promise.error(onError);
});
</script>
在 Fiddler 中,我可以看到,AngularJS-HTTP-Get 请求的标头有一个“Origin: null”条目,这似乎与问题有关。我认为,如果改为“null”,则值为“http://localhost”,它应该可以工作。
谁能帮帮我?
谢谢!
【问题讨论】:
-
你必须实现 CORS 服务器端,因为端口不同。就浏览器而言,这构成了不同的起源
标签: angularjs cors asp.net-web-api2