如何避免jquery ajax中使用wcf服务的跨域策略?
答
如果您希望跨域调用从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。
答
我得到它使用JQuery(1.5.1)$ .ajax CrossDomain设置为true。
我不明白为什么当在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;
}
什么想法?
答
铬/火狐不会让我这样做,直到我明确设置
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
在我的电话
嗨,我已经创建了一个类型的post.When我发送来自jQuery的AJAX数据的服务它不工作。类型GET的方法工作正常。 – user601367 2011-05-11 06:10:32
JSONP /跨域调用只能使用HTTP GET。更多的信息在这里:http://stackoverflow.com/questions/2699277/post-data-to-jsonp – 2011-05-11 07:02:50
如何通过AJAX跨域'POST'请求? – 2011-11-24 11:58:12