自定义绑定命令

本示例演示如何在不使用配置文件或 Windows Communication Foundation (WCF) 生成的客户端的情况下,编写命令性代码来定义和使用自定义绑定。本示例将 HTTP 传输提供的功能与可靠会话通道结合在一起,用于创建基于 HTTP 的可靠绑定。此示例基于实现计算器服务的入门示例

提示

本主题的末尾介绍了此示例的设置过程和生成说明。

在客户端和服务上,创建包含两个绑定元素(可靠会话和 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.