【问题标题】:how to avoid cross domain policy in jquery ajax for consuming wcf service?如何避免 jquery ajax 中使用 wcf 服务的跨域策略?
【发布时间】:2011-08-06 20:41:49
【问题描述】:

jquery ajax 中如何避免跨域策略使用 wcf 服务??

我需要在 web.config 中对跨域策略进行哪些更改?

【问题讨论】:

    标签: jquery wcf cross-domain


    【解决方案1】:

    如果您想要从 javascript 到 WCF 的跨域调用,您必须使用 JSONP。要将 JSONP 支持添加到 WCF,您必须在 WebHttpBinding 中定义它。配置应如下所示:

    <bindings>
      <webHttpBinding>
        <binding name="crossDomain" crossDomainScriptAccessEnabled="true" />
      </webHttpBinding>
    </binding>
    <behaviors>
      <endpointBehavior>
        <behavior name="restBehavior">
          <webHttp />
        </behavior>
      </endpointBehavior>
    </behaviors>
    <services>
      <service name="...">
        <endpoint address="" binding="webHttpBinding" bindingConfiguration="crossDomain"
                  contract="..." behaviorConfigurations="restBehavior" /> 
      </service>
    </services>
    

    对于 jQuery 部分检查,例如 this article

    【讨论】:

    • 嗨,我创建了一个 post 类型的服务。当我从 jquery ajax 发送数据时它不起作用。GET 类型的方法工作正常。
    • JSONP / 跨域调用仅适用于 HTTP GET。更多信息在这里:stackoverflow.com/questions/2699277/post-data-to-jsonp
    • 如何通过ajax发出cross domainPOST请求?
    • @ThePoet:你不能这样 - 这只是启用 JSONP,它通常会得到一个 json 响应,然后传递给eval。使用 JSONP 时不能发帖。如果您需要进行跨域 POST,您应该查看 CORS。
    【解决方案2】:

    我使用设置为 true 的 JQuery (1.5.1) $.ajax CrossDomain 设置让它工作。

    我还不明白为什么在 WCF (.NET4) 服务上使用属性 [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 时,调用成功而没有跨域设置(到 web.config和 $.ajax),当使用属性 [WebGet(ResponseFormat = WebMessageFormat.Json)] 时,它需要 webconfig 和 $.ajax 调用中的跨域设置。如果我在没有跨域设置的情况下使用 WebGet 属性,我会收到“不允许的方法”错误。

    使用WCF代码:

    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)] // requires crossdomain settings 
    //[ScriptMethod(ResponseFormat = ResponseFormat.Json)] // no crossdomain settings required
    public string GetNumber(string id)
    {
        return "query response on id: " + id;
    }
    

    有什么想法吗?

    【讨论】:

      【解决方案3】:

      chrome/firefox 在我明确设置之前不会让我这样做

      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
      

      在我的电话中

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-28
        • 2012-08-23
        • 2016-10-22
        • 1970-01-01
        • 1970-01-01
        • 2012-04-23
        • 1970-01-01
        • 2011-12-30
        相关资源
        最近更新 更多