【问题标题】:AngularJS CORS error when passing post params to WCF service将帖子参数传递给 WCF 服务时出现 AngularJS CORS 错误
【发布时间】:2018-04-22 23:58:12
【问题描述】:

有一个本地运行的 WCF 网络服务,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;
        }

我在 CORS 的 system.webserver 标记中的服务的 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>`

`

我的 Angular 端 API 调用看起来像这样

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

`

只有在访问具有参数的 api 时才会出现此错误。当在 Postman 中运行相同的 API 调用时能够获得响应。任何帮助将不胜感激。

【问题讨论】:

  • 你能调试 WCF 服务吗?有可能消息正在到达,但任何其他服务器错误都将导致 405,因为 OPTIONS 预检请求尚未得到答复。另一个小评论:从 $http.post 调用中删除 'Access-Control-Allow-Origin': '*',该标头不应由客户端发送;这是服务器问题
  • 通过邮递员调用时能够得到web服务api的响应
  • 不是 Postman 的专家,但由于它不是浏览器,因此可能没有发送 OPTIONS 请求,因此您没有遇到 CORS 问题。问题出在浏览器和服务器之间
  • 是的,完全正确,选项在服务器端处理不正确。

标签: javascript angularjs wcf cors


【解决方案1】:

最终解决方案出现了,在 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 代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    • 2012-12-01
    • 2014-03-10
    • 1970-01-01
    相关资源
    最近更新 更多