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

时间:2011-04-16 11:06:41

标签: jquery wcf cross-domain

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

我需要在web.config中为跨域策略做些什么?

3 个答案:

答案 0 :(得分:5)

如果您想要从javascript到WCF的跨域调用,您必须使用JSONP。要向WCF添加JSONP支持,您必须在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

答案 1 :(得分:2)

我使用JQuery(1.5.1)$ .ajax CrossDomain设置设置为true来使用它。

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

使用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;
}

任何想法?

答案 2 :(得分:2)

chrome / firefox在我明确设置

之前不会让我这样做
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

在我的电话中