WCF服务

来源:互联网 发布:佛山网络推广 招聘 编辑:程序博客网 时间:2024/05/29 18:58

什么是WCF

Windows Communication
Foundation(WCF)是由微软研发的一组数据通信的应用程序开发接口,它是.NET框架的一部分。由 .NET Framework
3.0 开始引入。

  
  WCF的最终目标是通过进程或不同的系统、通过本地网络或是通过Internet收发客户和服务之间的消息。
  WCF合并了Web服务、.net Remoting、消息队列和Enterprise Services的功能并集成在Visual Studio中,专门用于面向服务开发。

Demo

1.新建WCF服务应用程序

2.删除系统生成的两个文件IService1.cs与Service1.svc。

3.添加自定义的WCF服务文件——User.svc,此时vs2010会自动生成WCF接口文件IUser.cs.

4.在IUser中定义WCF方法PrintName,在User.svc.cs对该接口的方法进行实现。

using System.ServiceModel;namespace WCFService{    [ServiceContract] //定义服务契约,表示该接口可以被外部调用    public interface IUser    {        [OperationContract] //操作契约,表示该方法可以被外部调用        string PrintName(string name);    }}namespace WCFService{    public class User : IUser    {        public string PrintName(string name)        {            string resName = string.Format("WCF服务demo,Name:{0}", name);            return resName;        }    }}

5.F5可以在WCF测试客户端打开该服务,也可以在IIS中创建该服务。

6.像发布网站一样在IIS中发布该服务
WCF服务

7.新建一个Web Form项目命名为“WCFClient”,添加一个asp.Net页面Test.aspx

8.在WCFClient项目中添加IIS中发布的WCF服务的引用。

9.在Test.aspx页面中添加以下代码:

<form id="form1" runat="server">     <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />    <asp:Button ID="submit" runat="server" Text="请输入Name" OnClick="btnClick" /></form>

10.在Test.aspx后台添加点击事件代码

protected void btnClick(object sender, EventArgs e)        {            UserClient user = new UserClient();            string result = user.PrintName(this.txtName.Text);            Response.Write(result);        }

11.F5运行打开Test.aspx页面,输入Name:“Mark”,即可在页面显示:

WCF服务demo,Name:Mark

服务调用成功。

通信过程

WCF能够建立一个跨平台的安全、可信赖、事务性的解决方案,是一个WebService,.Net Remoting,Enterprise Service,WSE,MSMQ的并集。

技术对比

技术对比表

WCF中的 Endpoint(终结点)

Endpoint = “A”+”B”+”C”

  1. A(Address):”地址”。这是一个URI地址标识,通过这个地址可以找到要调用的WCF服务。

  2. B(Binding):”绑定”。 Binding实现在Client和Service通信的所有底层细节。如:通信采用的编码(XML?Text?二进制?)、采用的传输协议(TCP?Http?)、采用的解决安全问题的机制(SSL?加密?)

  3. C(Contract):”契约”。 Contract暴露某个WCF 服务所提供的所有有效的方法。

配置文件

服务端的config

<?xml version="1.0" encoding="utf-8"?><configuration>  <appSettings>    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />  </appSettings>  <system.web>    <compilation debug="true" targetFramework="4.5" />    <httpRuntime targetFramework="4.5"/>  </system.web>  <system.serviceModel>    <behaviors>      <serviceBehaviors>        <behavior>                    <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>              <serviceDebug includeExceptionDetailInFaults="false"/>        </behavior>      </serviceBehaviors>    </behaviors>    <protocolMapping>        <add binding="basicHttpsBinding" scheme="https" />    </protocolMapping>        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />  </system.serviceModel>  <system.webServer>    <modules runAllManagedModulesForAllRequests="true"/>    <directoryBrowse enabled="true"/>  </system.webServer></configuration>

客户端的config

<?xml version="1.0" encoding="utf-8"?><configuration>    <system.web>      <compilation debug="true" targetFramework="4.5" />      <httpRuntime targetFramework="4.5" />    </system.web>    <system.serviceModel>        <bindings>            <basicHttpBinding>                <binding name="BasicHttpBinding_IUser" />            </basicHttpBinding>        </bindings>        <client>            <endpoint address="http://localhost:8020/User.svc" binding="basicHttpBinding"                bindingConfiguration="BasicHttpBinding_IUser" contract="WCFService.IUser"                name="BasicHttpBinding_IUser" />        </client>    </system.serviceModel></configuration>

为何客户端有endpoint节点,而服务端没有该节点呢?

答案是:我们把WCF寄宿在IIS上,而IIS默认监听的就是Http协议——[B确定了]并且地址也是相对于IIS上的文件地址——[A确定了],契约就更不用说了,找到User.svc什么都有了——[C确定了],所以在服务端就没有必要显示的写出endpoint节点。
服务器端的endpoint确定了,客户端的endpoint自然要和服务端去对应,所以IDE在生成客户端的配置文件里endpoint写的很详细的,而服务端却没有endpoint。

WCF宿主

WCF本身不能够独自运行,WCF在运行时必寄宿在“宿主程序”之上

WCF的宿主:可以是 Windows 服务、COM+应用程序、WAS(Windows Activation Services,Windows进程激活服务)、IIS、Windows应用程序,或简单的控制台应用程序及任何.net程序。

WCF服务应用程序与WCF服务库

WCF服务应用程序:是一个可以执行的程序,它有独立的进程,WCF服务类契约的定义,可以直接看到运行的效果,此项目模板基于IIS托管的程序。

WCF服务库:可以认为是一个包含WCF服务以及契约定义的类库。不能直接运行,但可以在其他项目里引用,有点类似于在Web项目中应用的类库。

控制台宿主

(1)WCF 服务类库(WCFLibrary),和创建WCF服务应用程序过程差不多。

(2)在解决方案下新建控制台输出项目 WCFConsole。

(3)添加 System.ServiceModel.dll 的引用。

(4)添加 WCF 服务类库(WCFLibrary)的项目引用。

using System;using WCFLibrary;using System.ServiceModel;using System.ServiceModel.Description;namespace WCFConsole{    class Program    {        static void Main(string[] args)        {            //创建宿主的地址            Uri baseAddress = new Uri("http://localhost:8010/User");            //创建宿主            using (ServiceHost host = new ServiceHost(typeof(User), baseAddress))            {                //向宿主中添加终结点                host.AddServiceEndpoint(typeof(IUser), new WSHttpBinding(), "");                //将HttpGetEnabled属性设置为true                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();                smb.HttpGetEnabled = true;                //将行为添加到Behaviors中                host.Description.Behaviors.Add(smb);                //打开宿主                host.Open();                Console.WriteLine("开启WCF的HTTP监听...");                Console.ReadLine();                host.Close();            }        }    }}

至此,控制台宿主创建完毕,他和IIS宿主功能一样,这样客户端就可以通过添加服务引用来使用WCF服务了。

winform宿主

(1)新建Windows窗体应用程序项目 WCForm。

(2)添加 System.ServiceModel.dll 的引用。

(3)添加 WCF 服务类库(WCFLibrary)的项目引用。

(4)添加应用程序配置文件App.config。

(5)创建宿主程序MainForm窗体,并修改App.config

<?xml version="1.0" encoding="utf-8" ?><configuration>  <system.serviceModel>    <services>      <service name="WCFLibrary.User">        <host>          <baseAddresses>            <add baseAddress="http://localhost:8010/User"/>          </baseAddresses>        </host>        <endpoint address="" binding="wsHttpBinding" contract="WCFLibrary.IUser"></endpoint>      </service>    </services>    <behaviors>      <serviceBehaviors>        <behavior>          <serviceMetadata httpGetEnabled="True"/>          <serviceDebug includeExceptionDetailInFaults="False"/>        </behavior>      </serviceBehaviors>    </behaviors>  </system.serviceModel></configuration>

(6)winform后台代码

using System;using WCFLibrary;using System.ServiceModel;using System.Windows.Forms;using System.Configuration;namespace WCFForm{    public partial class MainForm : Form    {        ServiceHost host;        public MainForm()        {            InitializeComponent();        }        //应用程序加载        private void MainForm_Load(object sender, EventArgs e)        {            host = new ServiceHost(typeof(User));            //打开宿主            host.Open();            this.lblState.Text = "启动WCF的HTTP监听....";        }        //应用程序关闭        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)        {            host.Close();            this.lblState.Text = "关闭WCF的HTTP监听....";        }    }}