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技术社区】872894940

更多文章可以关注博主个人站点:IT技术小趣屋

posted @ 2018-11-28 23:50 江湖逍遥 阅读(...) 评论(...) 编辑 收藏