2016-12-31 64 views
0

当我尝试从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 
    } 
} 
+0

错误消息明确指出原点是“http:// localhost:64035”。资源位于'http:// localhost:57997 /'。端口64035正在尝试对源端口57997进行跨源访问。另外'OPTIONS'应该是一个允许的方法。 – georgeawg

+0

soo如何克服此解决方案 –

回答

0

可以通过禁用Chrome浏览器的Web安全选项处理它通过从chrome.exe所在的文件夹位置执行命令。首先关闭chrome的所有实例。然后下面的命令

的chrome.exe - 禁用网络安全

您可以在服务器端处理它,而过滤来服务器的所有请求,头添加到这样的响应运行。

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*"); 
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS"); 
+0

我已经在WeApi文件中添加了它的结果甚至相同结果 –

+1

您的此行 “string [] allowedOrigin = new string [] {”http:// localhost:57997 /“};” 应该像这样string [] allowedOrigin = new string [] {“http:// localhost:64035 /”}; –

相关问题