艾伟:WCF以Json格式返回对象,客户端以JS调用显示


很少写东西,但是看到别人写的文章自己又禁不住写点,写了有时候又觉得不好意思给大家看!

今天好不容易鼓起勇气写点……

这几天看了一些WCF的资料

第一感觉是:这玩艺太深了

第二感觉是:这玩艺,挺麻烦的(光配置就搞不明白)

今天调了半天,好不容易把这个返回Json对象,在客户端展示的实例给整理出来了。下面分享给大家

此实例:以IIS为Host承载

1、先建一个WCF Service

建一个ServiceContract接口1[ServiceContract]

2publicinterfaceIJsonWCFService
3{
4///
5///GetJsonResult
6///
7///
8///
9///
10///
11///为实现Json序列化,添加属性
12///[WebInvoke(ResponseFormat=WebMessageFormat.Json,BodyStyle=WebMessage
BodyStyle.Wrapped)]
13///
14///
15[OperationContract]
16[WebInvoke(ResponseFormat=WebMessageFormat.Json,BodyStyle=WebMessageBody
Style.Wrapped)]
17JsonResultGetJsonResult(stringname,stringaddress,stringphone);
18}

实现这个接口

1publicclassJsonWCFService:IJsonWCFService
2{
3#regionIJsonWCFServiceMembers
4///
5///Implementtheinterface
6///
7///Name
8///Address
9///PhoneNumber
10///JsonResult
11publicJsonResultGetJsonResult(stringname,stringaddress,stringphone)
12{
13JsonResultresult=newJsonResult(name,address,phone);
14returnresult;
15}
16#endregion
17}

这个地方好像忘记了一个返回的DataContract类

1[DataContract]
2publicclassJsonResult
3{
4///
5///Construct
6///
7publicJsonResult(stringname,stringaddress,stringphone)
8{
9_name=string.Format("Name:{0}",name);
10_address=string.Format("Address:{0}",address);
11_phoneNumber=string.Format("PhoneNubmer:{0}",phone);
12}
13
14privatestring_name;
15///
16///Name
17///
18[DataMember]
19publicstringName
20{
21get{return_name;}
22set{_name=value;}
23}
24privatestring_address;
25///
26///Address
27///
28[DataMember]
29publicstringAddress
30{
31get{return_address;}
32set{_address=value;}
33}
34privatestring_phoneNumber;
35///
36///PhoneNumber
37///
38[DataMember]
39publicstringPhoneNumber
40{
41get{return_phoneNumber;}
42set{_phoneNumber=value;}
43}

2、为实现Json序列化设置,我们还得添加一个WebContentTypeMapper

(此类最终会用在Service的配置文件中)

1usingSystem.ServiceModel.Channels;
2
3namespaceMicrosoft.Ajax.Samples
4{
5///
6///JsonContentTypeMapper
7///用在配置中
8///
9publicclassJsonContentTypeMapper:WebContentTypeMapper
10{
11publicoverrideWebContentFormatGetMessageFormatForContentType(stringcontentType)
12{
13if(contentType=="text/javascript")
14{
15returnWebContentFormat.Json;
16}
17else
18{
19returnWebContentFormat.Default;
20}
21}
22}
23}

3、添加svc文件,便于发布Service

svc文件其实是十分简单的一个文件,以下是SVC文件中的内容,可以将此文件添加在网站项目的根目录,也可以是一个子目录。对此没有太多的要求。

1<%@ServiceHostLanguage="C#"Debug="true"Service="JsonWCFService"%>

4、添加web.config文件

WCFService中相当一部分知识是关于配置的,关于这些内容,一直在“研究”。还没有理出来一个比较顺的思路!

1xmlversion="1.0"?>
2<configuration>
3<appSettings/>
4<connectionStrings/>
5<system.web>
6
7system.web>
8<system.serviceModel>
9<behaviors>
10<endpointBehaviors>
11<behaviorname="jsonWcfBehavior">
12<webHttp/>
13behavior>
14endpointBehaviors>
15behaviors>
16<bindings>
17<customBinding>
18<bindingname="JsonMapper">
19
20<webMessageEncodingwebContentTypeMapperType="Microsoft.Ajax.Samples.JsonC
ontentTypeMapper,JsonContentTypeMapper,Version=1.0.0.0,Culture=neutral,PublicKeyToken=
null"
>
21webMessageEncoding>
22<httpTransportmanualAddressing="true"/>
23binding>
24customBinding>
25bindings>
26<services>
27<servicename="JsonWCFService">
28
29<endpointaddress="ajaxEndpoint"behaviorConfiguration="jsonWcfBehavior"
30binding="customBinding"
31bindingConfiguration="JsonMapper"contract="IJsonWCFService">
32endpoint>
33service>
34services>
35system.serviceModel>
36configuration>

到此为止,Service算是提供完了,可以运行一下看一下结果。

5、剩下的就是客户端的问题,我们来实现客户端调用WCFService的方法

客户端的内容不算太复杂,其中一好多部分内容我自己觉得:应该是固定写法

1<htmlxmlns="http://www.w3.org/1999/xhtml">
2<head>
3<title>JsonServiceRresulttitle>
4
5<scriptlanguage="javascript"type="text/javascript">
6functionCall(contentType){
7varname=document.getElementById("name").value;
8varaddress=document.getElementById("address").value;
9varphone=document.getElementById("phone").value;
10if(name&&address&&phone){
11//CreateHTTPrequest
12varxmlHttp=CreateHttpRequest();
13if(xmlHttp==null){
14alert("此实例只能在支持Ajax的浏览器中运行");
15}
16
17//Createresulthandler
18xmlHttp.onreadystatechange=function(){
19if(xmlHttp.readyState==4){
20varresult=eval("("+xmlHttp.responseText+")").GetJsonResultResult;
21varhtml=result.Name+"
";
22html+=result.Address+"
";
23html+=result.PhoneNumber+"
";
24document.getElementById("divMessagePanel").innerHTML=html;
25}
26}
27//初始化操作Url
28//tools.self.com:站点发布的域名
29//ajaxEndpoint请参阅web.config中配置
30//ajaxEndpoint"behaviorConfiguration="jsonWcfBehavior"
31//binding="customBinding"
32//bindingConfiguration="JsonMapper"contract="IJsonWCFService">
33//
34//GetJsonResult:服务方法名称
35varurl="http://tools.self.com/Json/JsonWCFService.svc/ajaxEndpoint/GetJsonResult";
36
37//初始化Json消息
38varbody='{"name":"';
39body=body+name+'","address":"';
40body=body+address+'","phone":"';
41body=body+phone+'"}';
42//发送Http请求
43xmlHttp.open("POST",url,true);
44xmlHttp.setRequestHeader("Content-type",contentType);
45xmlHttp.send(body);
46}
47}
48//创建HttpRequest对象
49functionCreateHttpRequest(){
50varhttpRequest;
51try{
52httpRequest=newXMLHttpRequest();
53}
54catch(e){
55try{
56httpRequest=newActiveXObject("Msxml2.XMLHTTP");
57}
58catch(e){
59try{
60httpRequest=newActiveXObject("Microsoft.XMLHTTP");
61}
62catch(e){
63returnnull;
64}
65}
66}
67returnhttpRequest;
68}
69
70script>
71head>
72<body>
73<h1>
74JsonContentTypeMapper客户端页面h1>
75<p>
76姓名:
77<inputtype="text"id="name"/>p>
78<p>
79地址:
80<inputtype="text"id="address"/>p>
81<p>
82电话号码:
83<inputtype="text"id="phone"/>p>
84<inputtype="button"onclick="returnCall('text/javascript');"value="application/json"/><br/>
85<br/>
86<divstyle="font-size:16px;color:red"id="divMessagePanel">
87div>
88body>
89html>
90
91

到此整个功能算是完成了。

Service,Host,Client都有了,功德圆满,大家可以运行看一下结果。

优质内容筛选与推荐>>
1、File
2、11月15日站立会议
3、网赚经验之谈:成为高手之路 (摘自http://www.cnblogs.com/onlytiancai/archive/2008/11/13/1332977.html)
4、What’s the difference between Taxonomies and Ontologies? - Ask Dr. Search
5、为什么要写年终总结


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn