当我尝试从MVC访问的WebAPI,我得到这个错误的XMLHttpRequest无法加载的http://本地主机:57997 /主页/获取
XMLHttpRequest cannot load http://localhost:57997/Home/Get. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:64035' is therefore not allowed acces
Service.Js
app.service('MyService', function ($http) {
var ApiAddress = "http://localhost:57997/";
this.GetWebData = function() {
var Getdatas= $http({
url: ApiAddress + 'Home/Get',
type: 'GET',
dataType: 'json',
params: JSON.stringify(),
content:{'content-type' :'application/Json'}
})
return Getdatas;
}
});
控制器.Js
app.controller('WebCtrls', function ($scope,MyService) {
$scope.Hello = "Hello angular How r u...";
$scope.GetDb = function() {
alert('Hello..');
var SerData = MyService.GetWebData();
SerData.then(function (d) {
$scope.Emp = d.data;
})
}
})
的WebAPI
public JsonResult Get()
{
var x = prod.GetEmployees();
return new JsonResult { Data = x, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
的Global.asax
在全球的WebAPI文件我写娄代码为跨页起源
protected void Application_BeginRequest()
{
string[] allowedOrigin = new string[] { "http://localhost:57997/" };
var origin = HttpContext.Current.Request.Headers["Origin"];
if (origin != null && allowedOrigin.Contains(origin))
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", origin);
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST");
//Need to add more later , will see when required
}
}
错误消息明确指出原点是“http:// localhost:64035”。资源位于'http:// localhost:57997 /'。端口64035正在尝试对源端口57997进行跨源访问。另外'OPTIONS'应该是一个允许的方法。 – georgeawg
soo如何克服此解决方案 –