自定义绑定命令

命令性示例演示如何编写命令性代码来定义和使用自定义绑定,而无需使用配置文件或 Windows Communication Foundation (WCF) 生成的客户端。 此示例结合了 HTTP 传输和可靠会话通道提供的功能,以创建基于 HTTP 的可靠绑定。 此示例基于《入门指南》,实现了计算器服务。

注释

本示例的设置过程和生成说明位于本主题末尾。

在客户端和服务上,将创建一个自定义绑定,其中包含两个绑定元素(Reliable Session 和 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("http://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 示例执行了 One-Time 设置程序

  2. 若要生成解决方案的 C# 或 Visual Basic .NET 版本,请按照 生成 Windows Communication Foundation 示例中的说明进行操作。

  3. 若要在单台计算机或跨计算机配置中运行示例,请按照 运行 Windows Communication Foundation 示例中的说明进行操作。

另请参阅