MultipleEndpoints 示例演示如何在服务上配置多个终结点,以及如何从客户端与每个终结点通信。 此示例基于入门指南。 服务配置已被修改,以定义两个支持 ICalculator 协定的终结点,但是每个终结点都使用不同的绑定并位于不同的地址。 已修改客户端配置和代码,以便与两个服务终结点通信。
注释
本示例的设置过程和生成说明位于本主题末尾。
服务 Web.config 文件已修改为定义两个终结点,每个终结点都支持同一 ICalculator 协定,但在不同的地址使用不同的绑定。 第一个终结点在基址上使用 basicHttpBinding 绑定定义,并且该绑定没有启用安全性。 第二个终结点通过 wsHttpBinding 绑定在 {baseaddress}/secure 中定义,该绑定默认情况下使用 Windows 身份验证和 WS-Security 进行保护。
<service
name="Microsoft.ServiceModel.Samples.CalculatorService"
behaviorConfiguration="CalculatorServiceBehavior">
<!-- This endpoint is exposed at the base address provided by host:
http://localhost/servicemodelsamples/service.svc -->
<endpoint address=""
binding="basicHttpBinding"
contract="Microsoft.ServiceModel.Samples.ICalculator" />
<!-- secure endpoint exposed at {base address}/secure:
http://localhost/servicemodelsamples/service.svc/secure -->
<endpoint address="secure"
binding="wsHttpBinding"
contract="Microsoft.ServiceModel.Samples.ICalculator" />
...
</service>
这两个端点也在客户端上配置。 这些终结点的名称是给定的,以便调用方可以将所需的终结点名称传递到客户端的构造函数中。
<client>
<!-- Passing "basic" into the constructor of the CalculatorClient
class selects this endpoint.-->
<endpoint name="basic"
address="http://localhost/servicemodelsamples/service.svc"
binding="basicHttpBinding"
contract="Microsoft.ServiceModel.Samples.ICalculator" />
<!-- Passing "secure" into the constructor of the CalculatorClient
class selects this endpoint.-->
<endpoint name="secure"
address="http://localhost/servicemodelsamples/service.svc/secure"
binding="wsHttpBinding"
contract="Microsoft.ServiceModel.Samples.ICalculator" />
</client>
客户端使用这两个终结点,如以下代码所示。
static void Main()
{
// Create a client to the basic endpoint configuration.
CalculatorClient client = new CalculatorClient("basic");
Console.WriteLine("Communicate with basic endpoint.");
// call operations
DoCalculations(client);
// Close the client and release resources.
client.Close();
// Create a client to the secure endpoint configuration.
client = new CalculatorClient("secure");
Console.WriteLine("Communicate with secure endpoint.");
// Call operations.
DoCalculations(client);
// Close the client and release resources.
client.Close();
Console.WriteLine();
Console.WriteLine("Press <ENTER> to terminate client.");
Console.ReadLine();
}
运行客户端时,将显示与两个终结点的交互。
Communicate with basic endpoint.
Add(100,15.99) = 115.99
Subtract(145,76.54) = 68.46
Multiply(9,81.25) = 731.25
Divide(22,7) = 3.14285714285714
Communicate with secure endpoint.
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.
设置、生成和运行示例
确保已为 Windows Communication Foundation 示例 执行One-Time 安装过程。
若要生成解决方案的 C# 或 Visual Basic .NET 版本,请按照 生成 Windows Communication Foundation 示例中的说明进行操作。
若要在单台计算机或跨计算机配置中运行示例,请按照 运行 Windows Communication Foundation 示例中的说明进行操作。