2016-12-31 65 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 /」}; –

相關問題