7

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?

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
user601367
  • 2,308
  • 12
  • 34
  • 44

3 Answers3

5

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.

Mike Bailey
  • 12,479
  • 14
  • 66
  • 123
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • hi,i have created a service of type post.When i am sending data from jquery ajax it is not working.Method of type GET working fine. – user601367 May 11 '11 at 06:10
  • 1
    JSONP / cross domain calls work only with HTTP GET. More info here: http://stackoverflow.com/questions/2699277/post-data-to-jsonp – Ladislav Mrnka May 11 '11 at 07:02
  • 2
    how to make a `cross domain` `POST` request via ajax? – Zain Shaikh Nov 24 '11 at 11:58
  • @ThePoet: You cannot this way - this is only enabling JSONP which generally gets a json response which is then passed to `eval`. You cannot post when using JSONP. If you need to do cross domain POST you should look into CORS. – Ladislav Mrnka Nov 26 '15 at 10:46
2

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?

Pierre
  • 56
  • 5
2

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

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

in my calls

Micah
  • 10,295
  • 13
  • 66
  • 95