WCF入門教程

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

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

  • 服務器端

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

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

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

 

   具體步驟爲:   工具

   1 建立新的控制檯應用程序項目。 新建項目對話框中,選中「Visual Basic」「Visual C#」,並選擇控制檯應用程序模板,並命名爲Service 使用默認的位置。學習

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

   3、爲項目提供對 System.ServiceModel 命名空間的引用:右擊解決方案資源管理器中的「Service」項目,選擇添加引用項,在彈出的對話框中的「.NET」選項卡里的組件名稱中選擇「System.ServiceModel」,而後單擊肯定命令行

 

   下面是編程步驟:代理

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

      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技術小趣屋博主公衆號以下: 

 

相關文章
相關標籤/搜索