WCF Restful Service Get / Post請求

 

Rest 它是用於建立分佈式超文本媒體的一種架構方式,咱們能夠經過標準的HTTP(GET,POST,PUT,DELETE)操做來構建基於面向資源的軟件架構方式(Resource-Oriented Architecture (ROA))。它是獨立於任何技術或者平臺的,因此人們常常將符合這種操做規範的服務稱爲「RESTful services」。由於WCF可以構建符合這種規範的服務,因此咱們常常稱之爲 WCF Restful Services。web

因爲傳統的WCF Service可使用tcp,net.msmq,http等協議進行數據交換,而且採用了RPC(Remote Procedure Call)的工做方式,客戶端須要添加對服務端的引用才能完成。可是WCF Restful Service徹底使用Http協議來進行,而且無需添加客戶端引用,因此方便不少。json

 WebInvoke架構

其中,Method 方法主要是代表能夠接受客戶端的請求類型,這裏有四種:GET,POST,PUT,DELETE,其中GET爲請求數據,POST爲更新數據,PUT爲新增數據,DELETE表明着刪除數據。app

而後ResponseFormat 則表明着返回的數據組織,若是是Json則代表客戶端會接收到Json數據,若是是XML則代表客戶端會接收到XML組織的數據。BodyStyle 表明返回數據的包裝對象,若是是Bare則代表數據無任何包裝,原生數據返回;若是是Wrapped則代表數據會在最外層包裝一個當前函數名稱加上Result的套。好比對於Delete對象,則會返回 DeleteResult:{******},會形成DataContractJsonSerializer沒法進行反序列化。tcp

UriTemplate 主要用於指定操做的URI路徑,只要用戶輸入了合法路徑並採用了正確的請求方式,就會觸發該函數。分佈式

最後說到的就是URI後面跟的參數的問題,因爲函數只能接受string類型的,因此若是傳入參數是string類型,則可使用UriTemplate = "{bookID}"的路徑,反之,則須要加上/?param1={paramname}的方式ide

 

服務端函數

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Runtime.Serialization;
 5 using System.ServiceModel;
 6 using System.ServiceModel.Web;
 7 using System.Text;
 8 
 9 namespace IISWCF
10 {
11     // 注意: 使用「重構」菜單上的「重命名」命令,能夠同時更改代碼和配置文件中的接口名「IService1」。
12     [ServiceContract]
13     public interface IService1
14     {
15 
16         #region TEST
17 
18         [OperationContract(Name = "TestPost")]
19         [WebInvoke(Method = "POST", UriTemplate = "TestPost/{str}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
20         UserInfo TestPost(string str);
21 
22         [OperationContract, WebInvoke(Method = "GET", UriTemplate = "TestGet1")]
23         string TestGet1();
24 
25         [OperationContract(Name = "TestGet2")]
26         [WebGet(UriTemplate = "TestGet2/{Code}/{Card}",
27             BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml)]
28         UserInfo TestGet2(string Code, string Card);
29 
30         #endregion
31     }
32 
33 
34     // 使用下面示例中說明的數據約定將複合類型添加到服務操做。
35     [DataContract]
36     public class UserInfo
37     {
38          [DataMember]
39         public string Name { get; set; }
40          [DataMember]
41         public string Code { get; set; }
42          [DataMember]
43         public string Card { get; set; }
44     }
45 }
服務契約

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Runtime.Serialization;
 5 using System.ServiceModel;
 6 using System.ServiceModel.Web;
 7 using System.Text;
 8 
 9 namespace IISWCF
10 {
11     // 注意: 使用「重構」菜單上的「重命名」命令,能夠同時更改代碼、svc 和配置文件中的類名「Service1」。
12     // 注意: 爲了啓動 WCF 測試客戶端以測試此服務,請在解決方案資源管理器中選擇 Service1.svc 或 Service1.svc.cs,而後開始調試。
13     public class Service1 : IService1
14     {
15         #region TEST
16 
17         public UserInfo TestPost(string str)
18         {
19             UserInfo u = new UserInfo();
20             u.Name = str;
21             return u;
22         }
23 
24         public string TestGet1()
25         {
26             return "調用成功!";
27         }
28 
29         public UserInfo TestGet2(string Code, string Card)
30         {
31             UserInfo u = new UserInfo();
32             u.Code = Code;
33             u.Card = Card;
34             return u;
35         }
36 
37         #endregion
38         
39     }
40 }
服務實現

 

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <configuration>
 3   <system.web>
 4     <compilation debug="true" targetFramework="4.0" />
 5   </system.web>
 6   <system.serviceModel>
 7     <services>
 8       <service behaviorConfiguration="GetPostBehavior" name="IISWCF.Service1">
 9         <endpoint address="" behaviorConfiguration="GetPostEndBehaviors" binding="webHttpBinding" 
10                   contract="IISWCF.IService1">
11         </endpoint>
12         <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
13       </service>
14     </services>
15     <behaviors>
16       <endpointBehaviors>
17         <behavior name="GetPostEndBehaviors">
18           <webHttp />
19         </behavior>
20       </endpointBehaviors>
21       <serviceBehaviors>
22         <behavior name="GetPostBehavior">
23           <serviceMetadata httpGetEnabled="true" />
24           <serviceDebug includeExceptionDetailInFaults="false" />
25         </behavior>
26       </serviceBehaviors>
27     </behaviors>
28     <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
29   </system.serviceModel>
30   <system.webServer>
31     <modules runAllManagedModulesForAllRequests="true"/>
32     <!--
33         若要在調試過程當中瀏覽 Web 應用程序根目錄,請將下面的值設置爲 True。
34         在部署以前將該值設置爲 False 可避免泄露 Web 應用程序文件夾信息。
35       -->
36     <directoryBrowse enabled="true"/>
37   </system.webServer>
38 
39 </configuration>
配置文件

 

客戶端代碼測試

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Net;
 6 using System.Text;
 7 
 8 namespace ClientPost
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             var url = "http://localhost:6729/Service1.svc";
15             try
16             {
17                 Console.WriteLine("Post Method TestPost");
18                 string parms = "張三";
19                 string method = "TestPost";
20                 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url + "/" + method + "/" + parms);
21                 request.Method = "POST";
22                 request.ContentType = "text/plain";
23                 Stream requestStram = request.GetRequestStream();
24                 requestStram.Close();
25                 HttpWebResponse myResponse = (HttpWebResponse)request.GetResponse();
26                 StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
27                 string ReqResult = reader.ReadToEnd();
28                 Console.WriteLine(ReqResult);
29                 Console.WriteLine();
30             }
31             catch (Exception ex)
32             {
33                 Console.WriteLine(ex.ToString());
34             }
35 
36             try
37             {
38                 Console.WriteLine("Get Method TestGet1");
39                 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + "/TestGet1");
40                 httpWebRequest.ContentType = "application/json";
41                 httpWebRequest.Method = "GET";
42                 httpWebRequest.Timeout = 20000;
43                 HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
44                 StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
45                 string responseContent = streamReader.ReadToEnd();
46                 httpWebResponse.Close();
47                 streamReader.Close();
48                 Console.WriteLine(responseContent);
49                 Console.WriteLine();
50             }
51             catch (Exception ex)
52             {
53                 Console.WriteLine(ex.ToString());
54             }
55 
56             try
57             {
58                 Console.WriteLine("Get Method TestGet2");
59                 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + "/TestGet2/code123/card456");
60                 httpWebRequest.ContentType = "application/json";
61                 httpWebRequest.Method = "GET";
62                 httpWebRequest.Timeout = 20000;
63                 HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
64                 StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
65                 string responseContent = streamReader.ReadToEnd();
66                 httpWebResponse.Close();
67                 streamReader.Close();
68                 Console.WriteLine(responseContent);
69             }
70             catch (Exception ex)
71             {
72                 Console.WriteLine(ex.ToString());
73             }
74             Console.ReadLine();
75         }
76     }
77 }
Get/Post請求


運行結果:url

源碼下載WCF-Post-Get.rar

相關文章
相關標籤/搜索