WCF以Json格式返回對象,客戶端以JS調用顯示
很少寫東西,但是看到別人寫的文章自己又禁不住寫點,寫了有時候又覺得不好意思給大家看!
今天好不容易鼓起勇氣寫點……
這幾天看了一些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 }
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 }
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 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 }
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>
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
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都有了,功德圓滿,大家可以運行看一下結果。
全站熱搜