【问题标题】:XMLHttpRequest cannot load http://localhost:57997/Home/GetXMLHttpRequest 无法加载 http://localhost:57997/Home/Get
【发布时间】:2016-12-31 22:03:36
【问题描述】:

当我尝试从 MVC 访问 WebApi 时,出现此错误

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;
  }
});

Controller.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 也应该是允许的方法。
  • 如何克服这个解决方案

标签: angularjs asp.net-mvc-4 asp.net-web-api


【解决方案1】:

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

chrome.exe --disable-web-security

您可以在过滤所有到达服务器的请求时在服务器端处理它,像这样将标头添加到响应中。

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

【讨论】:

  • 你的这一行 "string[] allowedOrigin = new string[] { "localhost:57997" };"应该是这样的 string[] allowedOrigin = new string[] { "localhost:64035" };
猜你喜欢
  • 2015-04-15
  • 2019-07-13
  • 1970-01-01
  • 2014-12-09
  • 2011-11-03
  • 2015-08-16
  • 1970-01-01
  • 2013-09-29
  • 2011-01-31
相关资源
最近更新 更多