实现jquery.ajax及原生的XMLHttpRequest调用WCF服务的方法
废话不多说,直接讲解实现步骤
一、首先我们需定义支持WEB HTTP方法调用的WCF服务契约及实现服务契约类(重点关注各attribute),代码如下:
//IAddService.cs
namespace WcfService1
{
[ServiceContract]
public interface IAddService
{
[OperationContract]
[WebInvoke(Method="POST",RequestFormat=WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.WrappedRequest)]
int Add(int a,int b);
}
}
//AddService.cs
namespace WcfService1
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class AddService : IAddService
{
public int Add(int a, int b)
{
return a + b;
}
}
}
二、然后就是创建一个WCF服务缩主的svc文件,方法有两种:
1.在.NET FRAMEWORK 4.0以前,采用如下代码:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<!--添加一个WCF服务文件(如:AddService.svc),文件内容修改成如下:--><%@ ServiceHost Language="C#" Debug="true" Service="WcfService1.AddService" %><!--配置WEB.CONFIG:--> <system.serviceModel> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> <bindings> </bindings> <behaviors> <serviceBehaviors> <behavior> <!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false 并删除上面的元数据终结点 --> <serviceMetadata httpGetEnabled="true"/> <!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息 --> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="AddServiceBehavior"> <enableWebScript /> </behavior> </endpointBehaviors> </behaviors> <services> <service name="WcfService1.AddService"> <endpoint address="" binding="webHttpBinding" contract="WcfService1.IAddService" behaviorConfiguration="AddServiceBehavior" ></endpoint> </service> </services> </system.serviceModel> |
2.在.NET FRAMEWORK 4.0及以后,采用如下代码:(无需创建SVC文件,直接在WEB.CONFIG文件中指定一个地址,重点关注:serviceHostingEnvironment 节点)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<system.serviceModel> <bindings> </bindings> <behaviors> <serviceBehaviors> <behavior> <!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false 并删除上面的元数据终结点 --> <serviceMetadata httpGetEnabled="true"/> <!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息 --> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> </behaviors> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"> <serviceActivations> <add relativeAddress="AddService.svc" service="WcfService1.AddService" factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"/> </serviceActivations> </serviceHostingEnvironment></system.serviceModel> |
创建好后,直接运行该工程,出现如下画面则表示运行成功:

三、在同工程下新增一个WEB页面(格式不限,ASPX,HTML都可以),然后实现WEB客户端调用WCF服务的代码,我这里分为两种方式来完成,一是采用原生的XMLHttpRequest来调用,二是采用jQuery.ajax来调用,其内部原理相同,在此只是为了让大家更清楚一些。
采用原生的XMLHttpRequest来调用代码如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
//简单封装一下:var $ = function (id) { return document.getElementById(id);};//获取原生的XMLHttpRequest对象function getXMLHTTPRequest() { var req = false; try { req = new XMLHttpRequest(); } catch (err) { try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (err) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (err) { req = false; } } } return req;}$("btnGet").onclick = function () { var xmlhttp = getXMLHTTPRequest(); xmlhttp.open("POST", "http://localhost:30348/AddService.svc/Add", true); xmlhttp.setRequestHeader("Content-type", "application/json"); xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var r = JSON.parse(xmlhttp.responseText); $("result").value = r.d; } }; xmlhttp.send('{"a":' + $("num1").value + ',"b":' + $("num2").value + '}');} |
采用jQuery.ajax来调用代码如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
var jq = jQuery.noConflict();jq("#btnGet").click(function () { alert("click"); jq.ajax("http://localhost:30348/AddService.svc/Add", { type: "POST", //dataType: "json", contentType: "application/json", data: '{"a":' + jq("#num1").val() + ',"b":' + jq("#num2").val() + '}', //data: 'a=' + jq("#num1").val() + '&b=' + jq("#num2").val(), success: function (data) { jq("#result").val(data.d); }, error: function (x, textStatus, errorThrown) { alert(textStatus); } });}); |
最终实现效果如下:

特别说明,以上实现只支持在同一域名下进行调用,跨域调用则会报错,下次我将分享跨域调用WCF服务的方法,敬请期待,不足之处,欢迎指出,谢谢!
浙公网安备 33010602011771号