how to avoid cross domain policy in jquery ajax for consuming wcf service??
What chages do i need to do in web.config for cross domain policy?
If you want cross domain calls from javascript to WCF you must use JSONP. To add JSONP support to WCF you must define it in WebHttpBinding
. The configuration should look like:
<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>
For jQuery part check for example this article.
I got it to work using the JQuery (1.5.1) $.ajax CrossDomain setting set to true.
What I don't understand yet is why it is that when using the attribute [ScriptMethod(ResponseFormat = ResponseFormat.Json)] on the WCF (.NET4) service, the call succeeds without the crossdomain setting (to web.config and $.ajax) and when using the attribute [WebGet(ResponseFormat = WebMessageFormat.Json)] it requires the crossdomain settings in webconfig and $.ajax call. If I use WebGet attribute without the crossdomain settings I'll get an "Method Not Allowed" error.
WCF code is used:
[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;
}
any ideas?
chrome/firefox wouldn't let me do this until i explicitly set
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
in my calls
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With