命令式自訂繫結

此範例會示範如何撰寫命令式程式碼,以便在不使用組態檔或 Windows Communication Foundation (WCF) 產生之用戶端的情況下定義與使用自訂繫結。這個範例會結合 HTTP 傳輸和可靠工作階段通道所提供的功能來建立可靠的 HTTP 架構繫結。這個範例是以實作計算機服務的使用者入門範例為基礎。

ms751491.note(zh-tw,VS.90).gif注意:
此範例的安裝程序與建置指示位於本主題的結尾。

用戶端與服務端上都會建立包含兩種繫結項目 (可靠工作階段與 HTTP) 的自訂繫結:

ReliableSessionBindingElement reliableSession = new ReliableSessionBindingElement();
reliableSession.Ordered = true;

HttpTransportBindingElement httpTransport = new HttpTransportBindingElement();
httpTransport.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous;
httpTransport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;

CustomBinding binding = new CustomBinding(reliableSession, httpTransport);

在服務端上使用繫結的方式,是將端點新增至 ServiceHost:

serviceHost.AddServiceEndpoint(typeof(ICalculator), binding, "");

在用戶端上,繫結會由 ChannelFactory 用來建立服務的通道:

EndpointAddress address = new EndpointAddress("https://localhost:8000/servicemodelsamples/service");
ChannelFactory<ICalculator> channelFactory = new ChannelFactory<ICalculator>(binding, address);
ICalculator channel = channelFactory.CreateChannel();

接著,這個通道會用來與服務互動:

// Call the Add service operation.
double value1 = 100.00D;
double value2 = 15.99D;
double result = channel.Add(value1, value2);
Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);

當您執行範例時,作業要求和回應會顯示在用戶端主控台視窗中。在用戶端視窗中按下 ENTER 鍵,即可關閉用戶端。

    Add(100,15.99) = 115.99
    Subtract(145,76.54) = 68.46
    Multiply(9,81.25) = 731.25
    Divide(22,7) = 3.14285714285714

    Press <ENTER> to terminate client.

若要設定、建置及執行範例

  1. 請確定您已執行 Windows Communication Foundation 範例的單次安裝程序

  2. 若要建置方案的 C# 或 Visual Basic .NET 版本,請遵循建置 Windows Communication Foundation 範例中的指示。

  3. 若要在單一或跨電腦的組態中執行本範例,請遵循執行 Windows Communication Foundation 範例中的指示。

請參閱

其他資源

自訂繫結範例

Send comments about this topic to Microsoft.
© 2007 Microsoft Corporation. All rights reserved.