命令式
這個範例示範如何使用程式碼以定義服務的 WsHttpBinding,而不是使用組態來定義 wsHttpBinding 繫結的方式。這個範例是以實作計算機服務的使用者入門範例為基礎。
![]() |
---|
此範例的安裝程序與建置指示位於本主題的結尾。 |
下列程式碼示範如何透過程式碼來命令式地定義繫結。
public static void Main()
{
WSHttpBinding binding = new WSHttpBinding();
binding.Name = "binding1";
binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
binding.Security.Mode = SecurityMode.Message;
binding.ReliableSession.Enabled = false;
binding.TransactionFlow = false;
Uri baseAddress = new Uri("https://localhost:8000/servicemodelsamples/service");
// Create a ServiceHost for the CalculatorService type and provide the base address.
using(ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), baseAddress))
{
serviceHost.AddServiceEndpoint(typeof(ICalculator), binding, baseAddress);
// Open the ServiceHostBase to create listeners and start listening for messages.
serviceHost.Open();
// The service can now be accessed.
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate service.");
Console.WriteLine();
Console.ReadLine();
// Close the ServiceHostBase to shutdown the service.
serviceHost.Close();
}
}
用戶端會建立要與服務通訊的通道,如下列範例程式碼所示。
WSHttpBinding binding = new WSHttpBinding();
binding.Name = "binding1";
binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
binding.Security.Mode = SecurityMode.Message;
binding.ReliableSession.Enabled = false;
binding.TransactionFlow = false;
String url = "https://localhost:8000/servicemodelsamples/service";
EndpointAddress address = new EndpointAddress(url);
ChannelFactory<ICalculator> channelFactory = new ChannelFactory<ICalculator>(binding,address);
ICalculator channel = channelFactory.CreateChannel();
當您執行範例時,作業要求和回應會顯示在用戶端主控台視窗中。在用戶端視窗中按下 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.
若要設定、建置及執行範例
若要建置方案的 C# 或 Visual Basic .NET 版本,請遵循建置 Windows Communication Foundation 範例中的指示。
若要在單一或跨電腦的組態中執行本範例,請遵循執行 Windows Communication Foundation 範例中的指示。
Send comments about this topic to Microsoft.
© 2007 Microsoft Corporation. All rights reserved.