天天看點

WCF揭秘——自定義綁定 (上)相關文章

一、什麼是綁定

綁定是預先配置好的信道棧,它代表了伺服器與用戶端之間的通信約定,每個綁定都會指定了通信所應用到的傳輸協調、編碼等屬性。在 Framework3.5中已經包含basicHttpBinding、wsHttpBinding、wsDualHttpBinding、 webHttpBinding、netTcpBinding、netNamedPipeBinding、netMsmqBinding、 netPeerTcpBinding、msmqIntegrationBinding、wsFedrationHttpBinding、 ws2007HttpBinding、ws2007FederationHttpBinding等多種綁定。其中不同的綁定支援不同的傳輸協定,在消息編 碼、傳輸安全、通訊方式、安全模式、可靠性會話、事務流方面有着不同的屬性,能夠滿足大部分資訊通訊的要求。

綁定類名稱

傳輸

編碼

消息版本

安全模式

可靠性會話

事務流

BasicHttpBinding

HTTP

文本

SOAP 1.1

不支援

WSHttpBinding

SOAP 1.2 WS-Addressing 1.0

消息

禁用

WS-AtomicTransactions

WSDualHttpBinding

啟用

WSFederationHttpBinding

NetTcpBinding

TCP

二進制

SOAP 1.2

OleTransactions

NetPeerTcpBinding

P2P

NetNamedPipesBinding

命名管道

NetMsmqBinding

MSMQ

MsmqIntegrationBinding

CustomBinding

自定義 

自定義

自定義  

二、自定義綁定元素

當預定義的綁定無法滿足使用者需求時,可以使用CustomBinding類開發自定義綁定,該類存在于 System.ServiceModel.Channels命名空間。使用者可以根據需要綁定以下屬性: 事務(TransactionFlowBindingElement類)、可靠性會話(ReliableSessionBindingElement 類)、安全( SecurityBindingElement 類)、流安全、單工雙工工作模式、資訊編碼、傳輸綁定等,其中資訊編碼和傳輸綁定元素是自定義綁定的必要屬性,其他屬性使用者可根據需求制定。

傳輸綁定元素(必要),使用者可選其中一種傳輸綁定模式。

傳輸信道

傳輸綁定元素

綁定擴充

配置元素

TCP傳輸信道

TcpTransportBindingElement

TcpTransportElement

<tcpTransport>

HTTP傳輸信道

HttpTransportionBindingElement  

HttpTransportElement  

<httpTransport>

HTTPS傳輸信道

HttpTransportationBindingElement

HttpTransportElement

MSMQ傳輸信道

MSMQTransportBindingElement

MSMQTransportElement

<msmqTransport>

MSMQ內建傳輸信道

MSMQIntegrationBindingElement  

MSMQIntegrationBindingElement

<msmqIntegration>

命名管道傳輸信道

NamedPipeTransportBindingElement

NamedPipeTransportElement  

<namedPipeTransport>

P2P傳輸信道 

PeerTransportBindingElement

PeerTransportElement

<peerTransport>

UDP傳輸信道

UdpTransportBindingElement

UdpTransportElement

<udpTransport>

資訊編碼(必要),使用者可以選擇其中一種資訊編碼形式

                  1.TextMessageEncodingBindingElement,文本編碼

                  2.BinaryMessageEncodingBindingElement,二進制編碼

                  3.MtomMessageEncodingBindingElement,MOTM編碼

流安全綁定元素(可選),使用者可以選擇其中一種安全綁定形式

                  1.SslStreamSecurityBindingElement,SSL安全模式

                  2.WindowsStreamSecurityBindingElement,Window安全模式

通信傳輸(可選),使用者可以選擇單工或雙工其中一種模式

                  1.CompositeDuplexBindingElement,雙工傳輸模式

                  2.OneWayBindingElement,單工傳輸模式

CustomBinding相當于一個綁定的容器,使用者可以向裡面加入想要的綁定元素,定制一組适合使用的綁定方式。使用者可以分别使用代碼、配置檔案和綁定擴充類三種方式來開發自定義綁定,下面為大家一一說明。

三、使用代碼定制自定義綁定

下面以一個最基本的自定義綁定為例子,簡單說明一下如何使用代碼來定制綁定,首先建立一個服務契約

 1 namespace CustomBinding.Server 

 2 { 

 3     // 注意: 使用“重構”菜單上的“重命名”指令,可以同時更改代碼和配置檔案中的接口名“IExampleService”。 

 4     [ServiceContract(Namespace="Services")] 

 5     public interface IExampleService 

 6     { 

 7         [OperationContract] 

 8         string HelloWorld(string name); 

 9     } 

10    

11     public class ExampleService : IExampleService 

12     { 

13         public string HelloWorld(string name) 

14         { 

15             return "Hello " + name; 

16         } 

17     } 

18 } 

在伺服器端,首先建立一個CustomBinding自定義綁定對象,加入傳輸綁定元素HttpTransportBindingElement,然後加 入資訊編碼元素TextMessageEncodingBindingElement(注意,若使用 HttpTransportBindingElement傳輸方式時,可省略資訊編碼綁定,那麼系統将預設使用 TextMessageEncodingBindingElement編碼方式)。最後開放中繼資料,把服務行為的httpGetEnabled設定為 true。

 3     class Program 

 4     { 

 5         static void Main(string[] args) 

 6         { 

 7             CustomBinding(); 

 8         } 

 9  

10         public static void CustomBinding() 

11         { 

12             using (ServiceHost host = new ServiceHost(typeof(ExampleService), new Uri("http://localhost:8081/Services"))) 

13             { 

14                 //建立一個CustomBinding對象 

15                 System.ServiceModel.Channels.CustomBinding customBinding = new System.ServiceModel.Channels.CustomBinding(); 

16                 //設定資訊編碼 

17                 customBinding.Elements.Add(new TextMessageEncodingBindingElement()); 

18                 //設定傳輸綁定元素 

19                 customBinding.Elements.Add(new HttpTransportBindingElement()); 

20                 //綁定服務契約 

21                 host.AddServiceEndpoint(typeof(IExampleService), customBinding, "CustomService"); 

22                 //開放中繼資料 

23                 ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); 

24                 behavior.HttpGetEnabled = true; 

25                 host.Description.Behaviors.Add(behavior); 

26                 host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "CustomService/mex"); 

27                 //啟動服務 

28                 host.Open(); 

29                 Console.WriteLine("Service Start!"); 

30                 Console.ReadKey(); 

31                 host.Close(); 

32             } 

33         } 

34     } 

在用戶端添加服務引用,中繼資料路徑“http://localhost:8081/Services/CustomService/mex”,用戶端将對 應服務生成wsHttpBinding綁定,并使用TextMessageEncodingBindingElement文本編碼元素。最後調用服務測 試,若測試成功,系統将顯示測試結果:“Hello Leslie”。

1 <?xml version="1.0" encoding="utf-8" ?> 

 2 <configuration> 

 3     <system.serviceModel> 

 4         <bindings> 

 5           <!--由于自定義綁定是使用HttpTransportBindingElement綁定元素,是以用戶端将自動生成wsHttpBinding設定--> 

 6             <wsHttpBinding> 

 7               <!--注意綁定元素将對應使用TextMessageEncodingBindingElement資訊編碼元素--> 

 8                 <binding name="CustomBinding_IExampleService" closeTimeout="00:01:00" 

 9                     openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" 

10                     bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" 

11                     maxBufferPoolSize="524288" maxReceivedMessageSize="65536" 

12                     messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" 

13                     allowCookies="false"> 

14                     <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" 

15                         maxBytesPerRead="4096" maxNameTableCharCount="16384" /> 

16                     <reliableSession ordered="true" inactivityTimeout="00:10:00" 

17                         enabled="false" /> 

18                     <security mode="None"> 

19                         <transport clientCredentialType="Windows" proxyCredentialType="None" 

20                             realm="" /> 

21                         <message clientCredentialType="Windows" negotiateServiceCredential="true" /> 

22                     </security> 

23                 </binding> 

24             </wsHttpBinding> 

25         </bindings> 

26         <client> 

27             <endpoint address="http://localhost:8081/Services/CustomService" 

28                 binding="wsHttpBinding" bindingConfiguration="CustomBinding_IExampleService" 

29                 contract="ExampleService.IExampleService" name="CustomBinding_IExampleService" /> 

30         </client> 

31     </system.serviceModel> 

32 </configuration> 

33  

34 namespace CustomBinding.Client 

35 { 

36     class Program 

37     { 

38         static void Main(string[] args) 

39         { 

40             //建立服務對象,調用服務方法 

41             using (ExampleService.ExampleServiceClient example = new ExampleService.ExampleServiceClient()) 

42             { 

43                 string data=example.HelloWorld("Leslie"); 

44                 Console.WriteLine(data); 

45                 Console.ReadKey(); 

46             } 

47         } 

48     } 

49 } 

四、使用配置檔案設定自定義綁定

 3   <system.serviceModel> 

 4     <services> 

 5       <!--根據服務契約類的命名空間設定name名稱,設定服務行為defaultBehavior--> 

 6       <service name="CustomBinding.Server.ExampleService" behaviorConfiguration="defaultBehavior"> 

 7         <host> 

 8           <baseAddresses> 

 9             <!--綁定服務位址--> 

10             <add baseAddress="http://localhost:8082/CustomBinding.Server/ExampleService"/> 

11           </baseAddresses> 

12         </host> 

13         <!--加入自定義綁定--> 

14         <endpoint address="" contract="CustomBinding.Server.IExampleService" binding="customBinding" 

15                   bindingConfiguration="customBinding"/> 

16         <!--開放中繼資料--> 

17         <endpoint address="mex" contract="IMetadataExchange" binding="mexHttpBinding"/>  

18       </service> 

19     </services> 

20     <behaviors> 

21       <serviceBehaviors> 

22         <!--設定服務行為defaultBehavior,把httpGetEnabled設定為true--> 

23         <behavior name="defaultBehavior"> 

24           <serviceMetadata httpGetEnabled="true"/> 

25         </behavior> 

26       </serviceBehaviors> 

27     </behaviors> 

28     <bindings> 

29       <customBinding> 

30         <!--設定自定義綁定的屬性,把資訊編碼方式設定為textMessageEncoding文本形式,并把傳輸通道設定為httpTransport--> 

31         <!--把可靠性會話時間設定為30分鐘--> 

32         <binding name="customBinding"> 

33           <reliableSession inactivityTimeout="00:30:00"/> 

34           <textMessageEncoding/> 

35           <httpTransport/>  

36         </binding> 

37       </customBinding> 

38     </bindings> 

39   </system.serviceModel> 

40 </configuration> 

設定好config檔案後,啟動服務

12             using(ServiceHost host=new ServiceHost(typeof(ExampleService))) 

14                 Console.WriteLine("Service Start!"); 

15                 host.Open(); 

16                 Console.ReadKey(); 

17                 host.Close(); 

18             } 

19         } 

20     } 

21 } 

在用戶端添加服務引用,中繼資料路徑“http://lcoalhost:8082/CustomBinding.Server /ExampleService/mex”,用戶端将對應服務生成wsHttpBinding綁定,并使用TextMessageEncoding文本編 碼,值得注意的是客戶将對應伺服器端生成30分鐘可靠性會話。

 1 <?xml version="1.0" encoding="utf-8" ?> 

 5             <!--由于自定義綁定是使用HttpTransportBindingElement綁定元素,是以用戶端将自動生成wsHttpBinding設定--> 

16                     <!--注意用戶端将對應伺服器端生成30分鐘的可靠性會話--> 

17                     <reliableSession ordered="true" inactivityTimeout="00:30:00" 

18                         enabled="true" /> 

19                     <security mode="None"> 

20                         <transport clientCredentialType="Windows" proxyCredentialType="None" 

21                             realm="" /> 

22                         <message clientCredentialType="Windows" negotiateServiceCredential="true" /> 

23                     </security> 

24                 </binding> 

25             </wsHttpBinding> 

26         </bindings> 

27         <client> 

28             <endpoint address="http://localhost:8082/CustomBinding.Server/ExampleService" 

29                 binding="wsHttpBinding" bindingConfiguration="CustomBinding_IExampleService" 

30                 contract="ExampleService.IExampleService" name="CustomBinding_IExampleService" /> 

31         </client> 

32     </system.serviceModel> 

33 </configuration> 

34  

35 namespace CustomBinding.Client 

36 { 

37     class Program 

38     { 

39         static void Main(string[] args) 

40         { 

41             //建立服務對象,調用服務方法 

42             using (ExampleService.ExampleServiceClient example = new ExampleService.ExampleServiceClient()) 

43             { 

44                 string data=example.HelloWorld("Leslie"); 

45                 Console.WriteLine(data); 

46                 Console.ReadKey(); 

47             } 

48         } 

49     } 

50 } 

五、使用綁定擴充類實作自定義綁定

<a href="http://www.cnblogs.com/leslies2/archive/2011/10/14/2195800.html" target="_blank">自定義綁定(下)</a>

<a href="http://www.cnblogs.com/leslies2/archive/2011/01/26/1934163.html">簡單的WCF開發執行個體</a>

<a href="http://www.cnblogs.com/leslies2/archive/2011/01/26/1934889.html">使用AJAX+WCF進行頁面開發</a>

<a href="http://www.cnblogs.com/leslies2/archive/2011/08/03/2115091.html">共享資料契約</a>

<a href="http://www.cnblogs.com/leslies2/archive/2011/08/08/2129422.html">可靠性會話功能</a>

本文轉自 leslies2  51CTO部落格,原文連結:http://blog.51cto.com/79100812/702861

繼續閱讀