Share via


擷取中繼資料

這個範例會示範如何實作會動態擷取服務的中繼資料,以選擇要進行通訊之端點的用戶端。 此範例是以使用者入門範例為基礎。 服務已修改成公開兩個端點,一個是在基底位址使用 basicHttpBinding 繫結的端點,另一個是在 {baseaddress}/secure 使用 wsHttpBinding 繫結的安全端點。 此時用戶端並不是以端點位址與繫結設定,而是使用 MetadataExchangeClient 類別動態擷取服務的中繼資料,然後使用 WsdlImporter 類別將中繼資料當做 ServiceEndpointCollection 匯入。

ms752251.note(zh-tw,VS.100).gif注意:
此範例的安裝程序與建置指示位於本主題的結尾。

用戶端應用程式會使用匯入的 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();
    }
}

用戶端主控台視窗會顯示傳送至每個端點的作業,並顯示位址路徑與繫結名稱。

若要設定、建置及執行範例

  1. 請確定您已執行 Windows Communication Foundation 範例的單次安裝程序

  2. 若要建置方案的 C#、C++ 或 Visual Basic .NET 版本,請遵循建置 Windows Communication Foundation 範例中的指示。

  3. 若要在單一或跨機器的組態中執行本範例,請遵循Running the Windows Communication Foundation Samples中的指示進行。

ms752251.Important(zh-tw,VS.100).gif 注意:
這些範例可能已安裝在您的電腦上。 請先檢查下列 (預設) 目錄,然後再繼續。

<InstallDrive>:\WF_WCF_Samples

如果此目錄不存在,請移至用於 .NET Framework 4 的 Windows Communication Foundation (WCF) 與 Windows Workflow Foundation (WF) 範例 (英文),以下載所有 Windows Communication Foundation (WCF) 和 WF 範例。 此範例位於下列目錄。

<InstallDrive>:\WF_WCF_Samples\WCF\Basic\Client\RetrieveMetadata