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 範例 中的指示。