使用Angularjs和wcf restful service

时间:2016-11-03 08:32:02

标签: .net angularjs rest wcf cors

我是angularjs的新手,并尝试使用angularjs client来使用wcf restful服务。最初我曾尝试过http.get(url)并得到了CORS问题,我通过将以下代码放入我想要的wcf服务方法来解决打电话。

WebOperationContext.Current.OutgoingResponse.Headers.Add(" Access-Control-Allow-Origin"," ");          WebOperationContext.Current.OutgoingResponse.Headers.Add(" Access-Control-Allow-Methods"," POST,GET,OPTIONS"); WebOperationContext.Current.OutgoingResponse.Headers.Add(" Access-Control-Allow-Headers"," Content-Type,Accept"); *

现在,当我拨打电话(http.post)的方式与我做的相同时,我得到了回复而没有出现CORS问题。

但是当我在发帖时尝试传递JSON对象时,我再次开始遇到CORS问题。

我的帖子角度代码是:

 var requestData = {
            RequestUserName: "Abc1",
            RequestPass: "123"
        };

        var req = {
                    method: 'POST',
                    url: 'url',
                    headers: {
                        'Content-Type': 'application/json; charset=utf-8'
                    },
                    data: requestData
        };
         $http(req).success(function(){console.log("Success");
         $scope.userDetails = response.UserNameAuthenticationResult;}).error(function(){console.log("Error");});

我的WCF运营合同如下所示:

 [WebInvoke(Method="POST",UriTemplate="/Authenticate"
           ,RequestFormat=WebMessageFormat.Json
           ,ResponseFormat=WebMessageFormat.Json
           ,BodyStyle = WebMessageBodyStyle.Wrapped)]

        string UserNameAuthentication(Request request);

和方法实现如下:

 public string UserNameAuthentication(Request request)
       {
         WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
       WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
      WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept");

           return "true";
       }

我得到的错误如下:

  

** OPTIONS URL(匿名函数)@ angular.js:11442sendReq @ angular.js:11235serverRequest @ angular.js:10945processQueue @   angular.js:15552(匿名函数)@ angular.js:15568 $ eval @   angular.js:16820 $ digest @ angular.js:16636 $ apply @   angular.js:16928(匿名函数)@   angular.js:24551defaultHandlerWrapper @ angular.js:3398eventHandler @   angular.js:3386 localhost /:1 XMLHttpRequest无法加载   http://localhost:8733/TestService/Login/Authenticate。回应   预检请求未通过访问控制检查:否   '访问控制允许来源'标题出现在请求的上   资源。起源' http://localhost:14703'因此是不允许的   访问。响应的HTTP状态代码为405。

2 个答案:

答案 0 :(得分:0)

CORS是浏览器与服务器设置之间的交互。

发布请求和响应标头会很有用。

我假设您正在与其他域上的API进行交互,例如api.example.com而不是www.example.com。服务器可以设置Access-Control-Allow-Origins响应头。要允许所有来源作为临时措施,请将其设置为“*”而不是空字符串,但很快您应将其设置为您网站的实际来源,例如www.example.com

实际上,您可能不希望它完全打开,因为它可能存在安全风险,有人可能会创建您网站的虚假版本。

一起避免CORS的简单方法是使用代理服务器。这样所有请求都会转到同一个域(包括html和API)。如果运行节点应用程序,则可以使用node-http-proxy或类似方法。如果您有自定义标头或数据,这也可以避免预检请求。预检请求是您在实际请求之前在API上看到的OPTIONS请求。

以下是有关预检行为的更多信息: https://www.soasta.com/blog/options-web-performance-with-single-page-applications/

答案 1 :(得分:0)

由于无法理解OPTIONS方法,因此在服务器端看起来没有启用CORS。

也许试试这个:

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, OPTIONS");

        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
        HttpContext.Current.Response.End();
    }
}