WCF入門教程


 這一系列文章的內容是從MSDNCOPY過來的,講述的是最簡單的WCF程序示例:如何在控制台應用程序實現和承載WCF服務,以及如何創建、配置和使用WCF客戶端。

   文章主體可分為兩部分,分別介紹服務器端和客戶端的編程實現。細分的話,可以分為六項任務。

  • 服務器端

定義WCF服務協定(任務一)

   這是創建基本 Windows Communication Foundation (WCF) 服務和可以使用該服務的客戶端所需的六項任務中的第一項任務。

   創建基本 WCF 服務時,第一項任務是為與外界共享的服務創建協定,並在其中描述如何與該服務進行通信。

 

   具體步驟為:   

   1 創建新的控制台應用程序項目。 新建項目對話框中,選中“Visual Basic”“Visual C#”,並選擇控制台應用程序模板,並命名為Service 使用默認的位置。

   2、將默認的Service 命名空間更改為 Microsoft.ServiceModel.Samples

   3、為項目提供對 System.ServiceModel 命名空間的引用:右擊解決方案資源管理器中的“Service”項目,選擇添加引用項,在彈出的對話框中的“.NET”選項卡里的組件名稱中選擇“System.ServiceModel”,然后單擊確定

 

   下面是編程步驟:

   1、為 System.ServiceModel 命名空間添加一個 using 語句。      

      using System.ServiceModel;

   2、創建一個新的ICalculator 接口,並將 ServiceContractAttribute 屬性應用於該接口,並將 Namespace 值設置為“http://Microsoft.ServiceModel.Samples” 此命名空間指定該服務在計算機上的路徑,並構成該服務的基址部分。 請注意,在通過采用方括號表示法的屬性來批注接口或類時,該屬性類可以從其名稱中去掉“Attribute”部分。

    [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")] 

    public interface ICalculator

   3、在接口中創建方法聲明,並將 OperationContractAttribute 屬性應用於每個要作為公共 WCF 協定的一部分公開的方法。    

   [OperationContract]

   double Add(double n1, double n2);

   [OperationContract]

   double Subtract(double n1, double n2);

   [OperationContract]

   double Multiply(double n1, double n2);

   [OperationContract]

   double Divide(double n1, double n2);

   

 

   下面是創建服務協定的完整代碼段:   

using System;

// Add the using statement for the Sytem.ServiceModel namespace

using System.ServiceModel;

namespace Microsoft.ServiceModel.Samples

{

  //  Define a service contract.

  [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]

  public interface ICalculator

  {

    //  Create the method declaration for the contract.

    [OperationContract]

    double Add(double n1, double n2);

    [OperationContract]

    double Subtract(double n1, double n2);

    [OperationContract]

    double Multiply(double n1, double n2);

    [OperationContract]

    double Divide(double n1, double n2);

  }

}

........(整個服務器端的代碼未完,等講完任務三時,再給出完整代碼)

 

實現WCF服務協定(任務二)

   1、創建一個新 CalculatorService 類,該類從用戶定義的 ICalculator 接口繼承而來並實現該接口定義的協定功能。   

   public class CalculatorService : ICalculator

   

   2、實現每個算術運算符的功能。

    

public double Add(double n1, double n2)

{

    double result = n1 + n2;

    Console.WriteLine("Received Add({0},{1})", n1, n2);

    // Code added to write output to the console window.

    Console.WriteLine("Return: {0}", result);

    return result;

}

 

public double Subtract(double n1, double n2)

{

    double result = n1 - n2;

    Console.WriteLine("Received Subtract({0},{1})", n1, n2);

    Console.WriteLine("Return: {0}", result);

    return result;

}

 

public double Multiply(double n1, double n2)

{

    double result = n1 * n2;

    Console.WriteLine("Received Multiply({0},{1})", n1, n2);

    Console.WriteLine("Return: {0}", result);

    return result;

}

 

public double Divide(double n1, double n2)

{

    double result = n1 / n2;

    Console.WriteLine("Received Divide({0},{1})", n1, n2);

    Console.WriteLine("Return: {0}", result);

    return result;

}

 

   在創建和實現了服務協定后,下一步是運行該服務。 運行服務由三個步驟組成:配置、承載和打開服務。

配置、承載和運行服務(任務三)

  • 為服務配置基址   

    為服務的基址創建 Uri 實例。  URI 指定 HTTP 方案、本地計算機、端口號 8000,以及服務協定中為服務命名空間指定的服務路徑ServiceModelSample/Services    

    Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service");

  • 承載服務
  1. 創建一個新的 ServiceHost 實例以承載服務。 必須指定實現服務協定和基址的類型。 對於此示例,我們將基址指定為http://localhost:8000/ServiceModelSamples/Services,並將 CalculatorService 指定為實現服務協定的類型。

ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);

  1. 添加一個捕獲 CommunicationException  try-catch 語句,並在接下來的三個步驟中將該代碼添加到 try 塊中。
  2. 添加公開服務的終結點。 為此,必須指定終結點公開的協議、綁定和終結點的地址。 此例,將 ICalculator 指定為協定,將 WSHttpBinding 指定為綁定,並將 CalculatorService 指定為地址。 在這里請注意,我們指定的是相對地址。 終結點的完整地址是基址和終結點地址的組合 在此例中,完整地址是 http://localhost:8000/ServiceModelSamples/Services/CalculatorService

selfHost.AddServiceEndpoint(

    typeof(ICalculator),

    new WSHttpBinding(),

    "CalculatorService");

  1. 啟用元數據交換。 為此,必須添加服務元數據行為。 首先創建一個 ServiceMetadataBehavior 實例,將 HttpGetEnabled 屬性設置為 true,然后為服務添加新行為。

ServiceMetadataBehavior smb = new ServiceMetadataBehavior();

smb.HttpGetEnabled = true;

selfHost.Description.Behaviors.Add(smb);

  1. 打開 ServiceHost 並等待傳入消息。 用戶按 Enter 鍵時,關閉 ServiceHost

    selfHost.Open();

    Console.WriteLine("The service is ready.");

    Console.WriteLine("Press <ENTER> to terminate service.");

    Console.WriteLine();

    Console.ReadLine();

    // Close the ServiceHostBase to shutdown the service.

    selfHost.Close();

 

    下面是服務器端(即“Service”項目中program.cs文件中)的完整程序代碼:

using System;

using System.ServiceModel;

using System.ServiceModel.Description;

 

namespace Microsoft.ServiceModel.Samples

{

    // Define a service contract.

    [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]

    public interface ICalculator

    {

        [OperationContract]

        double Add(double n1, double n2);

        [OperationContract]

        double Subtract(double n1, double n2);

        [OperationContract]

        double Multiply(double n1, double n2);

        [OperationContract]

        double Divide(double n1, double n2);

    }

 

    // Service class that implements the service contract.

    // Added code to write output to the console window.

    public class CalculatorService : ICalculator

    {

        public double Add(double n1, double n2)

        {

            double result = n1 + n2;

            Console.WriteLine("Received Add({0},{1})", n1, n2);

            Console.WriteLine("Return: {0}", result);

            return result;

        }

 

        public double Subtract(double n1, double n2)

        {

            double result = n1 - n2;

            Console.WriteLine("Received Subtract({0},{1})", n1, n2);

            Console.WriteLine("Return: {0}", result);

            return result;

        }

 

        public double Multiply(double n1, double n2)

        {

            double result = n1 * n2;

            Console.WriteLine("Received Multiply({0},{1})", n1, n2);

            Console.WriteLine("Return: {0}", result);

            return result;

        }

 

        public double Divide(double n1, double n2)

        {

            double result = n1 / n2;

            Console.WriteLine("Received Divide({0},{1})", n1, n2);

            Console.WriteLine("Return: {0}", result);

            return result;

        }

    }

 

 

    class Program

    {

        static void Main(string[] args)

        {

 

            // Create a URI to serve as the base address.

            Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service");

 

            // Create ServiceHost

            ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);

            try

            {

                 //  Add a service endpoint.

                selfHost.AddServiceEndpoint(

                    typeof(ICalculator),

                    new WSHttpBinding(),

                    "CalculatorService");

 

                // Enable metadata exchange.

                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();

                smb.HttpGetEnabled = true;

                selfHost.Description.Behaviors.Add(smb);

 

                // Start (and then stop) the service.

                selfHost.Open();

                Console.WriteLine("The service is ready.");

                Console.WriteLine("Press <ENTER> to terminate service.");

                Console.WriteLine();

                Console.ReadLine();

 

                // Close the ServiceHostBase to shutdown the service.

                selfHost.Close();

            }

            catch (CommunicationException ce)

            {

                Console.WriteLine("An exception occurred: {0}", ce.Message);

                selfHost.Abort();

            }

        }

    }

}

若要運行服務,啟動項目文件夾下bin目錄中的 Service.exe即可。

 前面三篇文章是講服務器端的部署和運行,下面講講客戶端如何配置和使用。

創建WCF客戶端(任務四)

  1. 通過執行以下步驟,在 Visual Studio 2005 中為客戶端創建新項目:
    1. 在包含該服務(之前文章所述的服務)的同一解決方案中的解決方案資源管理器(位於右上角)中,右擊當前解決方案,然后選擇添加新項目
    2. 添加新項目對話框中,選擇“Visual Basic”“Visual C#”,選擇控制台應用程序模板,然后將其命名為 Client 使用默認的位置。
    3. 單擊確定
    4. 為項目提供對 System.ServiceModel 命名空間的引用:在解決方案資源管理器中右擊“Service”項目,從“.NET”選項卡上的組件名稱列中選擇“System.ServiceModel”,然后單擊確定
    5.  System.ServiceModel 命名空間添加 using 語句:using System.ServiceModel;
    6. 啟動在前面的步驟中創建的服務。(即打開在服務器項目中生成的Service.exe可執行文件)
    7. 通過執行以下步驟,使用適當的開關運行Service Model Metadata Utility Tool (SvcUtil.exe) 以創建客戶端代碼和配置文件:
      1. 通過選擇開始菜單中的“Microsoft Windows SDK”項下的“CMD Shell”,啟動 Windows SDK 控制台會話。
      2. 導航到要放置客戶端代碼的目錄。 如果使用默認設置創建 Client 項目,則目錄為 C:\Documents and Settings\<用戶名>\Documents\Visual Studio 2008\Projects\Service\Client
      3. 將命令行工具Service Model Metadata Utility Tool (SvcUtil.exe) 與適當的開關一起使用以創建客戶端代碼。 下面的示例生成服務的代碼文件和配置文件。

svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service

  1. Visual Studio 中將生成的代理添加到 Client 項目中,方法是在解決方案資源管理器中右擊“Client”並選擇添加現有項 然后選擇在上一步中生成的 generatedProxy.cs 文件。

配置WCF客戶端(任務五)

    Visual Studio 中,將在前一過程中生成的 App.config 配置文件添加到客戶端項目中。 在解決方案資源管理器中右擊該客戶端,選擇添加現有項,然后從 C:\Documents and Settings\<用戶名>\Documents\Visual Studio 2008\Projects\Service\Client\bin 目錄中選擇 App.config 配置文件。

    app.config添加到項目中后,就算是完成了wcf客戶端的配置。因為具體的配置信息,我們在使用svcutil.exe工具時,它就幫我們配置好並寫入了app.config文件。

 

使用WCF客戶端(任務六)

1、為要調用的服務的基址創建 EndpointAddress 實例,然后創建 WCF Client 對象。

    //Create an endpoint address and an instance of the WCF Client.

    EndpointAddress epAddress = new EndpointAddress("http://localhost:8000/ServiceModelSamples/Service/CalculatorService");

    CalculatorClient client = new CalculatorClient(new WSHttpBinding(), epAddress);

2、從 Client 內調用客戶端操作。

// Call the service operations.

// Call the Add service operation.

double value1 = 100.00D;

double value2 = 15.99D;

double result = client.Add(value1, value2);

Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);

 

// Call the Subtract service operation.

value1 = 145.00D;

value2 = 76.54D;

result = client.Subtract(value1, value2);

Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result);

 

// Call the Multiply service operation.

value1 = 9.00D;

value2 = 81.25D;

result = client.Multiply(value1, value2);

Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result);

 

// Call the Divide service operation.

value1 = 22.00D;

value2 = 7.00D;

result = client.Divide(value1, value2);

Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result);

3、在 WCF 客戶端上調用 Close

// Closing the client gracefully closes the connection and cleans up resources.

client.Close();

下面是客戶端的完整代碼:

using System;

using System.Collections.Generic;

using System.Text;

using System.ServiceModel;

 

namespace ServiceModelSamples

{

    class Client

    {

        static void Main()

        {

    //Step 1: Create an endpoint address and an instance of the WCF Client.

            EndpointAddress epAddress = new EndpointAddress("http://localhost:8000/ServiceModelSamples/Service/CalculatorService");

            CalculatorClient client = new CalculatorClient(new WSHttpBinding(), epAddress);

 

            // Step 2: Call the service operations.

            // Call the Add service operation.

            double value1 = 100.00D;

            double value2 = 15.99D;

            double result = client.Add(value1, value2);

            Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);

 

            // Call the Subtract service operation.

            value1 = 145.00D;

            value2 = 76.54D;

            result = client.Subtract(value1, value2);

            Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result);

 

            // Call the Multiply service operation.

            value1 = 9.00D;

            value2 = 81.25D;

            result = client.Multiply(value1, value2);

            Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result);

 

            // Call the Divide service operation.

            value1 = 22.00D;

            value2 = 7.00D;

            result = client.Divide(value1, value2);

            Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result);

 

            //Step 3: Closing the client gracefully closes the connection and cleans up resources.

            client.Close();

 

            Console.WriteLine();

            Console.WriteLine("Press <ENTER> to terminate client.");

            Console.ReadLine();

 

        }

    }

}

若要啟動客戶端,請在開始菜單中的“Microsoft Windows SDK”項下選擇“CMD Shell”,從而啟動 Windows SDK 控制台會話。 定位至 C:\Documents and Settings\<用戶名>\Documents\Visual Studio 2008\Projects\Service\Client\obj\Debug 目錄,鍵入 client,然后按Enter 操作請求和響應將出現在客戶端控制台窗口中,如下所示。

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.

 

最后,附上我的ASP.NET學習群,歡迎各位同行入群指導交流。技術群:【.NET技術社區】960640092

更多文章可以關注博主個人站點:IT技術小趣屋博主公眾號如下: 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM