how to avoid cross domain policy in jquery ajax fo

2019-01-08 17:47发布

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?

3条回答
▲ chillily
2楼-- · 2019-01-08 18:39

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.

查看更多
不美不萌又怎样
3楼-- · 2019-01-08 18:41

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

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

in my calls

查看更多
Root(大扎)
4楼-- · 2019-01-08 18:44

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?

查看更多
登录 后发表回答