WCF入门教程

来源:互联网 发布:java开发效率 编辑:程序博客网 时间:2024/05/19 03:26
 Windows Communication Foundation(WCF)是由微软发展的一组数据通信的应用程序开发接口,可以翻译为Windows通讯接口,它是.NET框架的一部分。由 .NET Framework 3.0 开始引入。

  WCF的最终目标是通过进程或不同的系统、通过本地网络或是通过Internet收发客户和服务之间的消息。

  WCF合并了Web服务、.net Remoting、消息队列和Enterprise Services的功能并集成在Visual Studio中支持若干绑定(原始HTTP、TCP、MSMQ和命名管道),这就允许你选择最合适的方式去进行传输和接收数据

  WCF专门用于面向服务开发。

 

更多点击:无废话WCF入门教程一[什么是WCF]

         老老实实学WCF

老老实实WCF第一篇 Hello WCF

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.ServiceModel;using System.ServiceModel.Description;namespace HelloWCFService{    class Program    {        static void Main(string[] args)        {            #region 宿主、服务、终结点            //第一步:建立基地址:            //localhost 表示本机,8000端口是随便选的,只要不和系统保留端口冲突就可以了,            //后面的MyService是服务地址,这个名字可以随便起,和服务实现类的名字相同也可以,他们没有联系            Uri baseAddress = new Uri("http://localhost:8000/MyService");            //第二步:建立服务(房子):            //WCF使用ServiceHost 的实例来承载服务,像我们这样的控制台程序,我们需要自己手动创建ServiceHost 实例,            //如果把服务寄存在IIS 中,那么IIS会替我们生成和管理ServiceHost 实例。            //ServiceHost 的构造函数接受两个参数,第2个参数基地址就不用说了;            //第1个参数是服务类型,注意看这里是HelloWCFService类,而不是IHelloWCFService接口,            //这里我们看出,服务的本体是服务实现类,而非协定接口,毕竟实实在在的逻辑在实现类里面,我们要寄宿的是它。            ServiceHost host = new ServiceHost(typeof(HelloWCFService), baseAddress);            //第三步:建立终结点并指定地址、绑定和服务协定:(为房子造门了,门是属于房子的,当然应该由房子来负责建立。)            //第1个参数指定了服务协定,请注意,这里是协定接口类型了,一个服务实现类可能实现多个服务协定接口,这样每个服务协定接口都有一个终结点与之对应了。            //第2个参数定义了绑定,即客户端与服务端沟通的方式,这里指定了一个wsHttpBinding的实例,            //第3个参数是终结点的地址。这里给了一个相对地址,终结点的最终地址将会把这个相对地址与基地址组合,即 http://localhost:8000/MyService/HelloWCFService              host.AddServiceEndpoint(typeof(IHelloWCFService), new WSHttpBinding(), "HelloWCFService");            #endregion            #region 启用元数据交换            //服务元数据行为对象(WCF服务元数据是WCF服务的核心部分服务地址(Address)、绑定(通信协议Binding)、契约(服务、操作、数据Contract)的原始描述信息)            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();            smb.HttpGetEnabled = true;//客户端就可用HTTP GET的方法从服务端下载元数据了            host.Description.Behaviors.Add(smb);//把这个服务元数据行为对象添加到宿主ServiceHost 对象的行为集合中去            #endregion            //启动宿主,开始服务            host.Open();            Console.WriteLine("Service is Ready");            Console.WriteLine("Press Any Key to Terminated...");            Console.ReadLine();            host.Close();              //测试            //http://localhost:8000/MyService        }    }    /// <summary>    /// 创建服务协定    /// </summary>    [ServiceContract]    interface IHelloWCFService    {        [OperationContract]        string HelloWCF();    }    /// <summary>    /// 实现服务协定    /// </summary>    public class HelloWCFService : IHelloWCFService    {        public string HelloWCF()        {            return "Hello WCF";        }    }}

老老实实WCF第二篇 配置WCF

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.ServiceModel;using System.ServiceModel.Description;namespace HelloWCFService{    class Program    {        static void Main(string[] args)        {            ServiceHost host = new ServiceHost(typeof(HelloWCFService));              //启动宿主,开始服务            host.Open();            Console.WriteLine("Service is Ready");            Console.WriteLine("Press Any Key to Terminated...");            Console.ReadLine();            host.Close();              //测试            //http://localhost:8000/MyService        }    }    /// <summary>    /// 创建服务协定    /// </summary>    [ServiceContract]    interface IHelloWCFService    {        [OperationContract]        string HelloWCF();    }    /// <summary>    /// 实现服务协定    /// </summary>    public class HelloWCFService : IHelloWCFService    {        public string HelloWCF()        {            return "Hello WCF";        }    }}

App.config (IIS程序是web.config 其他程序是app.config)

<?xml version="1.0" encoding="utf-8" ?><configuration>    <startup>         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />    </startup>  <system.serviceModel>    <services><!--容纳许多服务-->      <service name="HelloWCFService.HelloWCFService" behaviorConfiguration="metaExchange"><!--第1步:建设服务:服务配置元素标签;name属性,指定的时候后要用完全限定名(带着命名空间)-->        <host>          <baseAddresses><!--第2步:基地址-->            <add baseAddress="http://localhost:8000/MyService"/>          </baseAddresses>        </host>        <endpoint address="HelloWCFService" binding="wsHttpBinding" contract="HelloWCFService.IHelloWCFService" /><!--第3步:配置终结点-->        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/><!--第5步:建立元数据交换终结点-->      </service>    </services>        <behaviors><!--第4步:允许元数据交换-->      <serviceBehaviors>        <behavior name="metaExchange">          <serviceMetadata httpGetEnabled="true"/>        </behavior>      </serviceBehaviors>    </behaviors>      </system.serviceModel></configuration>

第三篇 在IIS中寄宿服务

(1) 建立IIS应用程序及物理路径

             

                                    

(2) 在应用程序路径下建立XXX.svc文件用于声明WCF入口和服务地址导航

<%@ServiceHost language=c# Debug="true" Service="LearnWCF.HelloWCFService"%>

(3) 在应用程序路径的子目录App_Code下建立 HelloWCFService.cs 文件用于定义和实现服务协定

using System;using System.ServiceModel;namespace LearnWCF{    [ServiceContract(SessionMode=SessionMode.Allowed)]    public interface IHelloWCF    {        [OperationContract]        string HelloWCF();    }    public class HelloWCFService : IHelloWCF    {        private int _Counter;        public string HelloWCF()        {            _Counter++;            return "Hello WCF!"+_Counter.ToString();        }    }}


(4) 在应用程序路径下建立web.config 用于配置服务。

<configuration>  <system.serviceModel>    <services>      <service name="LearnWCF.HelloWCFService" behaviorConfiguration="metadataExchange">        <endpoint address="http://192.168.5.6/IISService/HelloWCFService.svc" binding="wsHttpBinding" contract="LearnWCF.IHelloWCF"/>        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>      </service>    </services>    <behaviors>      <serviceBehaviors>        <behavior name="metadataExchange">          <serviceMetadata httpGetEnabled="true"/>        </behavior>      </serviceBehaviors>    </behaviors>  </system.serviceModel></configuration>


(5) 保持IIS为启动状态。




第四篇 初探通信--ChannelFactory

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.ServiceModel;namespace ChannelFactoryClient{    class Program    {        static void Main(string[] args)        {            //终结点地址            EndpointAddress address = new EndpointAddress("http://localhost/IISService/HelloWCFService.svc");            //绑定            WSHttpBinding binding = new WSHttpBinding();            //new通道工厂            ChannelFactory<IHelloWCFChannel> factory = new ChannelFactory<IHelloWCFChannel>(binding, address);            //有了工厂,接下来就要开始生产通道,通过执行通道工厂的CreateChannel方法来生产一个通道,            //由于工厂是用我们的协定接口创建的,所生产的通道也是实现这个接口的,我们可以直接用协定接口来声明其返回值。            IHelloWCFChannel channel = factory.CreateChannel();            //现在,通道已经打开,我们可以调用这个通道上的协定方法了。            string result = channel.HelloWCF();            channel.Close();            Console.WriteLine(result);            Console.ReadLine();        }    }    [ServiceContract]    public interface IHelloWCF    {        [OperationContract]        string HelloWCF();    }    //IClientChannel,这个接口提供了打开和关闭通道的方法    public interface IHelloWCFChannel : IHelloWCF, IClientChannel    {        }}


第五篇 再探通信--ClientBase

在上一篇中,我们抛开了服务引用和元数据交换,在客户端中手动添加了元数据代码,并利用通道工厂ChannelFactory<>类创建了通道,实现了和服务端的通信。然而,与服务端通信的编程模型不只一种,今天我们来学习利用另外一个服务类ClientBase<>来完成同样的工作,了解了这个类的使用方法,我们对服务引用中的关键部分就能够理解了。

 

ClientBase<>类也是一个泛型类,接受服务协定作为泛型参数,与ChannelFactory<>不同的是,这个类是一个基类,即抽象类,是不能实例化成对象直接使用的,我们需要自己写一个类来继承这个类,我们新写的类实例化出来就是客户端代理了,这个对象可以调用基类的一些受保护的方法来实现通信。ClientBase<>为我们封装的很好,我们只需要写个新类来继承他就可以了,通信的很多部分他都替我们做好了,比如我们不用进行去创建通道和打开通道的操作,直接调用协定方法就可以了。这也是服务引用和其他元数据生成工具(如svcutil)使用这个类来构造客户端代理的原因。

App.config

<?xml version="1.0" encoding="utf-8" ?><configuration>  <system.serviceModel>    <client>      <endpoint address="http://localhost/IISService/HelloWCFService.svc" binding="wsHttpBinding" contract="ClientBaseClient.IHelloWCF"/>    </client>  </system.serviceModel></configuration>

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.ServiceModel;namespace ClientBaseClient{    class Program    {        static void Main(string[] args)        {            //WSHttpBinding binding = new WSHttpBinding();            //EndpointAddress remoteAddress = new EndpointAddress("http://localhost/IISService/HelloWCFService.svc");            //HelloWCFClient client = new HelloWCFClient(binding,remoteAddress);            HelloWCFClient client = new HelloWCFClient();            string result = client.HelloWCF();            client.Close();            Console.WriteLine(result);            Console.ReadLine();        }    }    [ServiceContract]    public interface IHelloWCF    {        [OperationContract]        string HelloWCF();    }    public class HelloWCFClient : ClientBase<IHelloWCF>, IHelloWCF    {        public HelloWCFClient()            : base()        {        }        public HelloWCFClient(System.ServiceModel.Channels.Binding binding, EndpointAddress remoteAddress)            : base(binding, remoteAddress)        {                 }        public string HelloWCF()        {            return base.Channel.HelloWCF();        }    }}


 

              wcf 北风网     http://v.baidu.com/v?word=wcf+%B1%B1%B7%E7%CD%F8&ct=301989888&rn=20&pn=0&db=0&s=0&fbl=800#pn=0

 

 

 

0 0
原创粉丝点击