使用 AngularJs 调用 WCF REST 服务时出错

Calling WCF REST service using AngularJs giving error

我正在尝试使用 AngularJS[=28= 从我的本地计算机调用我的 WCF REST 服务(托管在非 PROD 环境中) ].但每次我得到

SEC7119:http://XXX/XXX/Web/rest/GeDetails 的 XMLHttpRequest 需要 CORS 预检。

SCRIPT7002:XMLHttpRequest:网络错误 0x80070005,访问被拒绝。

有什么方法可以使用 AngularJS 使用 WCF REST 服务吗?

谢谢!

您遇到了 CORS 错误。

您必须在 api -> enabling-cross-origin-requests-in-web-api

中启用 CORS

对于 WCF Rest 尝试 this

然后在您的 angular.config 中您必须:

    angular.module('myapp',[...])
    .config(function ($stateProvider, $urlRouterProvider, $httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
        // ...
  })

显然在最新的 AngularJS 版本中,您无需添加任何内容即可实现 work。但实际上对我来说是这样工作的。

希望对您有所帮助

在我的服务 global.asax 页面中使用了以下代码,并且其工作完美。

 protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }