JQuery Ajax消耗wcf服务应用程序

consuming wcf service application from JQuery Ajax

我已经构建了一个WCF Web应用程序,将其方法公开到获取启用的方法中

1
2
3
4
5
6
7
8
[OperationContract]
[WebGet]
string getStatistics();


[OperationContract]
[WebGet]
string getVenues(string BrandName, int limit);

并编辑配置文件:

1
<endpoint address="json" binding="webHttpBinding"  contract="foursquare2RDF.IVenue2rdf" behaviorConfiguration="restBehavior"/>

,并且在服务行为中:

1
2
3
4
5
 <endpointBehaviors>
<behavior name="restBehavior">
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>

我将服务托管在IIS上,并且在浏览器中也可以正常运行,因此当您点击:

1
http://localhost:83/venue2rdf.svc/json/getStatistics

返回良好的结果

问题是如果显示这些错误,我将无法使用此宁静的服务:

1
2
3
OPTIONS http://localhost:83/venue2rdf.svc/json/getStatistics?{'venues':'100'} 405 (Method Not Allowed)

XMLHttpRequest cannot load [http://localhost:83/venue2rdf.svc/json/getStatistics][1]. Origin null is not allowed by Access-Control-Allow-Origin.

我正在使用该代码调用服务:

1
2
3
4
5
6
7
8
9
10
11
12
$.ajax({
    type:"get",
    url: statisticsURL,
    data:"{}",
    contentType:"application/json; charset=utf-8",
    dataType:"json",
    success: function (msg) {
        eval("var x =" + msg.d);

        console.log(x);
    }
});

到目前为止,我所达到的目标:

  • 我试图用$ .getjson替换$ .ajax,就像在类似问题中所述
    并且错误405被清除,第二个错误刚刚出现
  • 我已经找到了一个启用了Ajax的WCF服务项目,但仍然不想迁移到新项目中
  • 我知道有类似的问题,但都不适合,显示出我发现的不同错误


您可能应该将其设为JSONP请求,因为您要跨域访问,并且遇到了相同的原始策略:

1
2
3
4
5
$.getJSON(stastatisticsURL +"?callback=?", success: function (msg) {
    eval("var x =" + msg.d);

    console.log(x);
});

?callback=?部分将jquery电话化为JSONP。我建议您仔细阅读什么是JSONP,因为它不是灵丹妙药。要在WCF服务上启用JSONP,请阅读:

C#WCF Web API JSONP


为使用jQuery使用跨域WCF REST服务,请在下面找到一个示例:

我的服务如下:

1
2
3
4
5
6
7
8
9
10
11
    [ServiceContract]
    public interface IJSONPService
    {
        [OperationContract]
        [WebGet]
        string GetDate();

        [OperationContract]
        [WebInvoke]
        string PostData(string name);
    }

现在,我用于上述服务的配置条目如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<services>
    <service name="Service.JSONPService">
        <endpoint address="" binding="webHttpBinding" behaviorConfiguration="json" bindingConfiguration="defaultRestJsonp" contract="Service.IJSONPService">
        </endpoint>
    </service>
</services>
<behaviors>
      <endpointBehaviors>
         <behavior name="json">
             <enableWebScript />
         </behavior>
   </behaviors>
</endpointBehaviors>
<webHttpBinding>
        <binding name="defaultRestJsonp" crossDomainScriptAccessEnabled="true">
          <readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxDepth="64" maxNameTableCharCount="2147483647" />
          <security mode="None" />
        </binding>
</webHttpBinding>

您需要注意绑定元素" defaultRestJsonp"中的crossDomainScriptAccessEnabled属性,该属性负责确定针对JSONP的请求,并适当地将来自查询的URL的响应转换为包含在回调方法中的响应字符串

现在从页面中执行以下JavaScript,以调用上述WCF REST服务,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function TestingWCFRestWithJsonp() {
                $.ajax({
                    url:"http://domain.com/Service/JSONPService.svc/GetDate",
                    dataType:"jsonp",
                    type:"GET",
                    timeout: 10000,
                    jsonpCallback:"MyCallback",
                    success: function (data, textStatus, jqXHR) {
                        alert(data);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {alert('error');

                    },
                    complete: function (jqXHR, textStatus) {alert('complete');
                    }
                });
            }
            function MyCallback(data) {
                alert(data);
            }

在$ .ajax方法调用中检出jsonpCallback属性。

对Web服务调用的原始请求如下所示:

1
2
3
GET http://localhost/Service/JSONPService.svc/GetDate?callback=MyCallback&_=1343391683779 HTTP/1.1
Host: localhost
Connection: keep-alive

WCF REST服务的原始响应如下所示:

1
2
3
4
5
6
7
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: application/x-javascript
Date: Fri, 27 Jul 2012 12:21:23 GMT
Content-Length: 27

MyCallback("27\\/07\\/2012");

注意:执行JSONP请求时,不会调用$ .ajax方法错误/完成/成功。