[Solution] 一步一步WCF(1) 快速入門


  Windows Communication Foundation(WCF)是由微軟開發的一系列支持數據通信的應用程序框架,可以翻譯為Windows 通訊開發平台。整合了原有的windows通訊的 .net Remoting,WebService,Socket的機制,並融合有HTTP和FTP的相關技術。是Windows平台上開發分布式應用最佳的實踐方式。

  安裝:在.net framework 3.0的時候已經內置了WCF。

 

  由於WCF的服務不能孤立地存在,需要寄宿於一個運行着的進程中,我們把承載WCF服務的進程稱為宿主。在本節將介紹2種服務寄宿服務,並分別通過Code和Config的方式為WCF服務綁定endpoint:

 

自我寄宿

1.建立項目

  • Service一個控制台應用,實現對wcf服務的寄宿,該項目引用System.ServiceMode程序集。(WCF框架的絕大部分實現和API定義在該程序集中)
  • Client一個控制台應用,實現對服務的調用端,該項目引用System.ServiceMode程序集。(生成的代理類繼承自該程序集)

 

2.創建契約(contract)

  WCF包含四種類型的契約:服務契約、數據契約、消息契約和錯誤契約。這里所指服務契約,用來聲明服務的所有操作。

  要使一個接口成為一個契約,需要為其貼上特性標簽。

using System.ServiceModel;

namespace Service
{
    [ServiceContract]
    public interface ICar
    {
        [OperationContract]
        string Run(int distance);
    }
}

  

3.實現服務

  實現接口方法即可

namespace Service
{
    public class CarService : ICar
    {
        public string Run(int distance)
        {
            return "行駛了" + distance;
        }
    }
}

 

4.開始寄宿

  WCF采用終結點的通信方式。終結點包括Address,Binding,Contract,簡稱ABC。

Address:  指定wcf的location

Binging:  指定傳輸協議。(tcp http msmq等)

Contract:  指定服務的Behavior。

using System;
using System.ServiceModel;

namespace Service
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var host = new ServiceHost(typeof(CarService)))
            {
                //指定服務的終結點,分別指定Contract,Binding,Address
                host.AddServiceEndpoint(typeof(ICar), new BasicHttpBinding(), "http://localhost:10000/Car");
                host.Open();
                Console.WriteLine("服務啟動成功");
                Console.Read();
            }
        }
    }
}

(已管理員身份啟動Service.exe)

 

服務以及寄宿成功,那我們怎么調用呢。實際上,這樣的方式是無法被調用的。客戶端引用的地址是服務的元數據。所以我們需要把服務的元數據暴露出來。

using System;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace Service
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var host = new ServiceHost(typeof(CarService)))
            {
                if (host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
                {
                    //服務的元數據 允許Get方式從下面的Url中獲取
                    var behavior = new ServiceMetadataBehavior
                    {
                        HttpGetEnabled = true,
                        HttpGetUrl = new Uri("http://localhost:10000/Car/Metadata")
                    };
                    host.Description.Behaviors.Add(behavior);
                }
                //指定服務的終結點,分別指定Contract,Binding,Address
                host.AddServiceEndpoint(typeof(ICar), new BasicHttpBinding(), "http://localhost:10000/Car");
                host.Opened += (o, e) => Console.WriteLine("服務啟動成功");
                host.Open();
                Console.Read();
            }
        }
    }
}

 

5.服務的調用

  服務的調用有2種方式,VS引用服務生成代理類,Code自定義代理類(需要保證Endpoint完全一致)。

Code自定義代理類:

using System;
using System.ServiceModel;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            //一致的終結點
            using (var channelFactory = new ChannelFactory<ICar>(new BasicHttpBinding(), "http://localhost:10000/Car"))
            {
                //手動創建代理類
                var proxy = channelFactory.CreateChannel();
                Console.WriteLine(proxy.Run(3));
            }
            Console.Read();
        }
    }
}

 

這里面的ICar(Contract),並非一定和wcf服務的ICar完全一致(指命名空間,所在程序集名稱),只需方法簽名一致即可。(由於是Contract仍需對應的特性)

using System.ServiceModel;

namespace Client
{
    [ServiceContract]
    interface ICar
    {
        [OperationContract]
        string Run(int distance);
    }
}

 

在管理員運行前面的Service.exe基礎上,運行Client.exe。

 

IIS寄宿

1.建立項目

 

2.文件結構

 

3.svc文件

svc文件相當於asmx文件,通過一個必須指令Service,指定具體的服務。如Service="WcfService.Service1"

在vs中,瀏覽器查看svc文件,svc的地址就是服務的地址。svc的地址+?wsdl是服務描述的地址。

 

4.服務的調用

和自我寄宿的服務類似,只用將Address改成svc的地址即可。 

注意,在新建svc文件的時候,vs會自動修改Web.config文件。(用來指定服務的元數據暴露行為)

<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">//指定默認的behavior
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

 

Config

以上基本均采用Code的方式實現WCF,實際上WCF非常靈活,一般都采用Config方式。或者Config+Code(都會生效)。

wcf的配置涉及到2種,服務的發布,服務的調用。

發布:

<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="meta">
          <serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost:10001/Car/Metadata"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="Service.CarService" behaviorConfiguration="meta">
        <endpoint address="http://localhost:10001/Car" binding="wsHttpBinding" contract="Service.ICar"></endpoint>
        <endpoint address="http://localhost:10001/Car2" binding="wsHttpBinding" contract="Service.ICar"></endpoint>
      </service>
    </services>
  </system.serviceModel>

 

調用:

<system.serviceModel>
    <client>
      <endpoint name="car" address="http://localhost:10001/Car" binding="wsHttpBinding" contract="Client.ICar"></endpoint>
    </client>
  </system.serviceModel>

當調用端采用配置方式的時候,代碼改成如下方式調用。(配置中name用來區分不同的endpoint,代碼中也使用對應的name創建信道棧Channel)

using System;
using System.ServiceModel;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var cf = new ChannelFactory<ICar>("car"))
            {
                Console.WriteLine(cf.CreateChannel().Run(3));
                Console.Read();
            }
        }
    }
}

 

上述內容概述了wcf Code和Config2種方式。在實際開發中,可以更簡單通過vs的引用服務生成代理類,配置wcf服務工具修改*.config。本文就不再贅述了。

 

代碼下載:等待整理

本文作者:Never、C

本文鏈接:http://www.cnblogs.com/neverc/p/4682394.html


免責聲明!

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



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