RetrieveMetadata 示例演示如何实现从服务动态检索元数据的客户端,以选择要与之通信的终结点。 此示例基于入门指南。 服务已修改为公开两个终结点:一个在基址处的终结点,使用basicHttpBinding
绑定,以及一个在 {baseaddress}/secure 的安全终结点,使用wsHttpBinding
绑定。 客户端无需通过终结点地址和绑定来配置,而是使用 MetadataExchangeClient 类动态检索服务的元数据,然后使用 ServiceEndpointCollection 类将元数据导入为 WsdlImporter。
注释
本示例的设置过程和生成说明位于本主题末尾。
客户端应用程序使用导入 ServiceEndpointCollection 来创建客户端来与服务通信。 客户端应用程序循环访问每个检索的终结点,并与实现 ICalculator
协定的每个终结点通信。 相应的地址和绑定随检索的终结点一起提供,以便客户端配置为与每个终结点通信,如以下示例代码所示。
// Create a MetadataExchangeClient for retrieving metadata.
EndpointAddress mexAddress = new EndpointAddress(ConfigurationManager.AppSettings["mexAddress"]);
MetadataExchangeClient mexClient = new MetadataExchangeClient(mexAddress);
// Retrieve the metadata for all endpoints using metadata exchange protocol (mex).
MetadataSet metadataSet = mexClient.GetMetadata();
//Convert the metadata into endpoints.
WsdlImporter importer = new WsdlImporter(metadataSet);
ServiceEndpointCollection endpoints = importer.ImportAllEndpoints();
CalculatorClient client = null;
ContractDescription contract = ContractDescription.GetContract(typeof(ICalculator));
// Communicate with each endpoint that supports the ICalculator contract.
foreach (ServiceEndpoint ep in endpoints)
{
if (ep.Contract.Namespace.Equals(contract.Namespace) && ep.Contract.Name.Equals(contract.Name))
{
// Create a client using the endpoint address and binding.
client = new CalculatorClient(ep.Binding, new EndpointAddress(ep.Address.Uri));
Console.WriteLine("Communicate with endpoint: ");
Console.WriteLine(" AddressPath={0}", ep.Address.Uri.PathAndQuery);
Console.WriteLine(" Binding={0}", ep.Binding.Name);
// Call operations.
DoCalculations(client);
//Closing the client gracefully closes the connection and cleans up resources.
client.Close();
}
}
客户端控制台窗口显示发送到每个终结点的操作,并显示地址路径和绑定名称。
设置、生成和运行示例
确保已为 Windows Communication Foundation 示例 执行One-Time 安装过程。
若要生成解决方案的 C#、C++ 或 Visual Basic .NET 版本,请按照 生成 Windows Communication Foundation 示例中的说明进行作。
若要在单台计算机或跨计算机配置中运行示例,请按照 运行 Windows Communication Foundation 示例中的说明进行操作。