Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to avoid cross domain policy in jquery ajax for consuming wcf service?

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?

like image 604
user601367 Avatar asked Apr 16 '11 11:04

user601367


3 Answers

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.

like image 173
Ladislav Mrnka Avatar answered Nov 10 '22 13:11

Ladislav Mrnka


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?

like image 41
Pierre Avatar answered Nov 10 '22 11:11

Pierre


chrome/firefox wouldn't let me do this until i explicitly set

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

in my calls

like image 2
Micah Avatar answered Nov 10 '22 13:11

Micah