将post params传递给WCF服务时出现AngularJS CORS错误

时间:2017-11-09 20:42:46

标签: javascript angularjs wcf cors

在本地运行WCF Web服务,POST API看起来像这样`

[WebInvoke(Method = "POST",
     BodyStyle = WebMessageBodyStyle.Wrapped,
     ResponseFormat = WebMessageFormat.Xml)]
        public string AssignLoopToLocations(int LoopID, int[] LocationIDs)
        {
            string strFileName = "AssignLoopToLocations_respone.xml";
            string strResult = GetFileData(strFileName);
            return strResult;
        }

我已在system.webserver标记中为CORS“

添加了服务的Web.config中的以下行
<httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
      </customHeaders>
    </httpProtocol>`

`

我的角度侧API调用看起来是这个`

factory.assignLocationsToLoop = function ( LoopID,locationList ) {
        var data = {
            LoopID : LoopID, LocationIDs : locationList
        } 
        return $http.post(mediaServicePath + "AssignLoopToLocations", data);

`  Chrome network debugger

我只有在访问具有参数的api时才会收到此错误。当在Postman中运行相同的API调用时,可以获得响应。任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

最后,通过在WCF服务中创建Global.cs文件,出现了解决方案,如下所示`

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", "GET, 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();
            }
        }

` 所有这些都没有在上面的Web.config中提到的httpProtocol代码。