WCF在4.0版本里有这么一个新的特性没有.svc的文件服务激活。
为了验证这么句话,".svc对于服务激活来说就是起到了这么一个映射的作用",今天就用"HelloWord"来验证它吧!.svc文件在我们建立WCF服务项目的时候VS会自动帮我们创建好(图1);我们也可以把它修改成下面的方式(图2)。
为了不偏移今天的主题,我们把图1的形式叫"猫";图2的形式叫"咪"。然后我们可以看看猫咪都是可以说"HelloWord".先来看我们"猫"的形式,也是VS为我们生成的结构:
首先我们来新建一个WCF的服务项目吧!叫IService吧,当我们创建好后,VS会为我们创建好如下图3.的样子。
由于我也是新学WCF的新人,为了更多新接触WCF和我一样的人,我还想多说几句关于服务端的话,首先服务内容是什么呢?服务内容就是我们的IService.cs文件里定义的契约决定,那就来看看我们IService.cs里的契约吧!
namespaceWCF_HelloService{///
namespaceWCF_HelloService{///
说完以"猫"的形式,那在来看看我们以"咪"的形式。信不信我们的"咪"也能叫"HelloWord",其实大家也都注意了开始为大家展示的"猫""咪"的结构对比,"咪"就是少了一个XXX.svc.cs的文件,而多了一个XXX.cs的文件,所以说变化也就在服务端的文件,那就来慢慢解开这个面纱吧!
这次还是新建一个项目叫Hello_WCF,还是添加以为服务项目经来,叫Hello.WCFService,进去把我们的契约IService1.cs改成IHelloWcfService.cs,并且给项目里添加一个文件夹叫Hello,如下图11.
<%@ServiceHostLanguage="C#"Debug="true"Service="Hello.WCFService.HelloWcfService"CodeBehind="~/Hello/HelloWcfService.cs"%>现在改好了,那就定义我们的契约吧!IHelloWcfService.cs:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Runtime.Serialization;usingSystem.ServiceModel;usingSystem.ServiceModel.Web;usingSystem.Text;namespaceHello.WCFService{[ServiceContract]publicinterfaceIHelloWcfService{[OperationContract]stringGetServiceMessage();}}来用我们新建HelloWcfService.cs的文件继承契约文件,并且实现它吧!
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingHello.WCFService;namespaceHello.WCFService{publicclassHelloWcfService:IHelloWcfService{publicstringGetServiceMessage(){return"HelloWord";}}}按照以前的做法,到这里我们就OK了,但是由于我们修改他的文件,所以我们还要修改他们的配置文件,为了更好的使用到元数据:先来看看它未被修改之前的配置,如下图14.
我们需要修改它成下面的形式:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceHelloWcf{classProgram{staticvoidMain(string[]args){HelloWCF.HelloWcfServiceClientHello=newHelloWCF.HelloWcfServiceClient();Console.WriteLine("从服务器端口下来的信息:");Console.WriteLine(Hello.GetServiceMessage());Console.ReadLine();}}}来看看结果如下图16:
其实对于新手来说WCF的配置有时会显得有点麻烦,其实在宿主程序那里我们的配置也可以用代码完成,就拿上面的"猫"结构的宿主,我们也可以使用下面的方式去实现:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.ServiceModel;usingWCF_HelloService;namespaceConsoleWCF{classProgram{staticvoidMain(string[]args){HelloService.ServiceClientHello=newHelloService.ServiceClient();ServiceHosthost=newServiceHost(typeof(WCF_HelloService.HelloService),newUri("Http://localhost:8000/WCF_HelloService"));host.AddServiceEndpoint(typeof(IService),newBasicHttpBinding(),"");host.Open();Console.WriteLine("监听服务端的信息是:"+Hello.ServiceMeaasge().ToString());Console.WriteLine("监听的终结点:Http://localhost:8000/WCF_HelloService");Console.WriteLine("结束监听");Console.Read();}}}上面这种写法,就可以不用去配置,但是看起来还是感觉配置的好,不用写这么多代码,那里看看运行的结果呗如图17: