检索元数据
本示例演示如何实现一个客户端,它能从服务中动态检索元数据以选择用来通信的终结点。此示例基于入门示例。已经对服务进行了修改以公开两个终结点:一个终结点位于基址并使用 basicHttpBinding 绑定,另一个安全终结点位于 {baseaddress}/secure 并使用 wsHttpBinding 绑定。不必使用终结点地址和绑定配置客户端,客户端可以使用 MetadataExchangeClient 类动态检索服务的元数据,然后使用 WsdlImporter 类以 ServiceEndpointCollection 的形式导入元数据。
![]() |
---|
本主题的最后介绍了此示例的设置过程和生成说明。 |
客户端应用程序使用导入的 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();
}
}
客户端控制台窗口将显示发送到每个终结点的操作,同时显示地址路径和绑定名称。
设置、生成和运行示例
若要生成 C#、C++ 或 Visual Basic .NET 版本的解决方案,请按照生成 Windows Communication Foundation 示例中的说明进行操作。
若要用单机配置或跨计算机配置来运行示例,请按照Running the Windows Communication Foundation Samples中的说明进行操作。
![]() |
---|
您的计算机上可能已安装这些示例。在继续操作之前,请先检查以下(默认)目录。
<安装驱动器>:\WF_WCF_Samples
如果此目录不存在,请访问针对 .NET Framework 4 的 Windows Communication Foundation (WCF) 和 Windows Workflow Foundation (WF) 示例(可能为英文网页),下载所有 Windows Communication Foundation (WCF) 和 WF 示例。此示例位于以下目录。
<安装驱动器>:\WF_WCF_Samples\WCF\Basic\Client\RetrieveMetadata
|