您的位置:知识库 » .NET技术

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

作者: 成峰  来源: 博客园  发布时间: 2008-12-26 23:18  阅读: 7559 次  推荐: 2   原文链接   [收藏]  

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

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

这几天看了一些WCF的资料

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

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

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

此实例:以IIS为Host承载

1、先建一个WCF Service

建一个ServiceContract接口 1 [ServiceContract]

 2 public interface IJsonWCFService
 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)]
17     JsonResult GetJsonResult(string name, string address, string phone);
18 }

实现这个接口

 

 1 public class JsonWCFService : IJsonWCFService
 2 {
 3     #region IJsonWCFService Members
 4     /// 
 5     /// Implement the interface
 6     /// 
 7     /// Name
 8     /// Address
 9     /// PhoneNumber
10     /// JsonResult
11     public JsonResult GetJsonResult(string name, string address, string phone)
12     {
13         JsonResult result = new JsonResult(name, address, phone);
14         return result;
15     }
16     #endregion
17 }

 

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

 

 1 [DataContract]
 2 public class JsonResult
 3 {
 4     /// 
 5     /// Construct
 6     /// 
 7     public JsonResult(string name, string address, string phone)
 8     {
 9         _name = string.Format("Name:{0}", name);
10         _address = string.Format("Address:{0}", address);
11         _phoneNumber = string.Format("PhoneNubmer:{0}", phone);
12     }
13 
14     private string _name;
15     /// 
16     /// Name
17     /// 
18     [DataMember]
19     public string Name
20     {
21         get { return _name; }
22         set { _name = value; }
23     }
24     private string _address;
25     /// 
26     /// Address
27     /// 
28     [DataMember]
29     public string Address
30     {
31         get { return _address; }
32         set { _address = value; }
33     }
34     private string _phoneNumber;
35     /// 
36     /// PhoneNumber
37     /// 
38     [DataMember]
39     public string PhoneNumber
40     {
41         get { return _phoneNumber; }
42         set { _phoneNumber = value; }
43     }

 

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

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

 

 1 using System.ServiceModel.Channels;
 2 
 3 namespace Microsoft.Ajax.Samples
 4 {
 5     /// 
 6     /// JsonContentTypeMapper
 7     /// 用在配置中
 8     /// 
 9     public class JsonContentTypeMapper : WebContentTypeMapper
10     {
11         public override WebContentFormat GetMessageFormatForContentType(string contentType)
12         {
13             if (contentType == "text/javascript")
14             {
15                 return WebContentFormat.Json;
16             }
17             else
18             {
19                 return WebContentFormat.Default;
20             }
21         }
22     }
23 }

 

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

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

 

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

 

4、添加web.config文件

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

 

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

 

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

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

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

 

 1 <html xmlns="http://www.w3.org/1999/xhtml">
 2 <head>
 3     <title>Json Service Rresulttitle>
 4 
 5     <script language="javascript" type="text/javascript">
 6         function Call(contentType) {
 7             var name = document.getElementById("name").value;
 8             var address = document.getElementById("address").value;
 9             var phone = document.getElementById("phone").value;
10             if (name && address && phone) {
11                 // Create HTTP request
12                 var xmlHttp = CreateHttpRequest();
13                 if (xmlHttp == null) {
14                     alert("此实例只能在支持Ajax的浏览器中运行");
15                 }
16 
17                 // Create result handler
18                 xmlHttp.onreadystatechange = function(){
19                     if (xmlHttp.readyState == 4) {
20                         var result = eval("(" + xmlHttp.responseText + " )").GetJsonResultResult;
21                         var html = result.Name + "
";
22                         html += result.Address + "
";
23                         html += result.PhoneNumber + "
";
24                         document.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:服务方法名称
35                 var url = "http://tools.self.com/Json/JsonWCFService.svc/ajaxEndpoint/GetJsonResult";
36 
37                 //初始化Json消息
38                 var body = '{"name":"';
39                 body = body + name + '","address":"';
40                 body = body + address + '","phone":"';
41                 body = body + phone + '"}';
42                 //发送Http请求
43                 xmlHttp.open("POST", url, true);
44                 xmlHttp.setRequestHeader("Content-type", contentType);
45                 xmlHttp.send(body);
46             }
47         }
48         //创建HttpRequest对象
49         function CreateHttpRequest() {
50             var httpRequest;
51             try {
52                 httpRequest = new XMLHttpRequest();
53             }
54             catch (e) {
55                 try {
56                     httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
57                 }
58                 catch (e) {
59                     try {
60                         httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
61                     }
62                     catch (e) {
63                         return null;
64                     }
65                 }
66             }
67             return httpRequest;
68         }        
69         
70     script>
71 head>
72 <body>
73     <h1>
74         JsonContentTypeMapper 客户端页面h1>
75     <p>
76         姓名:
77         <input type="text" id="name" />p>
78     <p>
79         地址:
80         <input type="text" id="address" />p>
81     <p>
82         电话号码:
83         <input type="text" id="phone" />p>
84     <input type="button" onclick="return Call('text/javascript');" value="application/json" /><br />
85     <br />
86     <div style="font-size: 16px; color: red" id="divMessagePanel">
87     div>
88 body>
89 html>
90 
91 

 

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

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

2
0
 
标签:WCF

.NET技术热门文章

    .NET技术最新文章

      最新新闻

        热门新闻