在上一篇博文中,我们创建了一个简单WCF应用程序,在其中介绍到WCF最重要的概念又是终结点,而终结点又是由ABC组成的。对于Address地址也就是告诉客户端WCF服务所在的位置,而Contract又是终结点中比较重要的一个内容,在WCF中,契约包括服务契约、数据契约、消息契约和错误契约,在本篇博文将解析下数据契约的内容,关于其他三种契约将会后面的博文中陆续介绍。
二、引出问题——WCF操作重载限制
C#语言是支持操作重载的,然而在WCF实现操作重载有一定的限制。错误的操作重载实例:
1 [ServiceContract(Name = "HellworldService", Namespace = "http://www.Learninghard.com")] 2 public interface IHelloWorld 3 { 4 [OperationContract] 5 string GetHelloWorld(); 6 7 [OperationContract] 8 string GetHelloWorld(string name); 9 }
如果你像上面一样来实现操作重载的话,在开启服务的时候,你将收到如下图所示的异常信息:
然而,为什么WCF不允许定义两个相同的操作名称呢?原因很简单,因为WCF的实现是基于XML的,它是通过WSDL来进行描述,而WSDL也是一段XML。在WSDL中,WCF的一个方法对应一个操作(operation)标签。我们可以参考下面一段XML,它是从一个WCF的WSDL中截取下来的。
<wsdl:import namespace="http://www.Learninghard.com" location="http://localhost:9999/GetHelloWorldService?wsdl=wsdl0"/> <wsdl:types/> <wsdl:binding name="BasicHttpBinding_HellworldService" type="i0:HellworldService"> <soap:binding transport="http://schemas.xmlsoap.org/soap/http"/> <wsdl:operation name="GetHelloWorldWithoutParam"> <soap:operation soapAction="http://www.Learninghard.com/HellworldService/GetHelloWorldWithoutParam" style="document"/> <wsdl:input> <soap:body use="literal"/> </wsdl:input> <wsdl:output> <soap:body use="literal"/> </wsdl:output> </wsdl:operation> <wsdl:operation name="GetHelloWorldWithParam"> <soap:operation soapAction="http://www.Learninghard.com/HellworldService/GetHelloWorldWithParam" style="document"/> <wsdl:input> <soap:body use="literal"/> </wsdl:input> <wsdl:output> <soap:body use="literal"/> </wsdl:output> </wsdl:operation> </wsdl:binding> <wsdl:service name="HelloWorldService"> <wsdl:port name="BasicHttpBinding_HellworldService" binding="tns:BasicHttpBinding_HellworldService"> <soap:address location="http://localhost:9999/GetHelloWorldService"/> </wsdl:port> </wsdl:service>
从上面的代码可以看出,每个Operation由一个operation XML Element表示,而每个Operation还应该具有一个能够唯一表示该Operation的ID,这个ID则是通过name属性来定义。Operation元素的Name属性通常使用方法名来定义,所以,如果WCF服务契约中,包含两个相同的操作方法名时,此时就违背了WSDL的规定,这也是WCF不可以使用操作重载的原因。
三、解决问题——WCF中实现操作重载
既然,找到了WCF中不能使用操作重载的原因(即必须保证Operation元素的Name属性唯一),此时,要想实现操作重载,则有两种思路:一是两个不同的操作名,二是实现一种Mapping机制,使得服务契约中的方法名映射到一个其他的方法名,从而来保证Name属性的唯一。对于这两种解决思路,第一种显然行不通,因为,方法名不同显然就不叫操作重载了,所以,我们可以从第二种解决思路下手。值得庆幸的是,这种解决思路,微软在实现WCF的时候已经帮我们实现好了,我们可以通过OperationContractAttribute的Name属性来为每个操作方法名定义一个别人,而生成的WSDL将使用这个别名来作为Operation元素的Name属性,所以我们只需要为两个相同方法名定义两个不同的别名就可以解决操作重载的问题了。既然有了思路,下面就看看具体的实现代码吧。具体服务契约的实现方法如下所示:
1 namespace Contract 2 { 3 [ServiceContract(Name = "HellworldService", Namespace = "http://www.Learninghard.com")] 4 public interface IHelloWorld 5 { 6 [OperationContract(Name = "GetHelloWorldWithoutParam")] 7 string GetHelloWorld(); 8 9 [OperationContract(Name = "GetHelloWorldWithParam")] 10 string GetHelloWorld(string name); 11 } 12 }
经过上面的步骤也就解决了在WCF中实现操作重载的问题。接下来让我们来完成一个完整的操作重载的例子。
定义契约完成之后,那就接着来实现下服务契约,具体的实现服务契约代码如下所示:
namespace Services { public class HelloWorldService : IHelloWorld { public string GetHelloWorld() { return "Hello World"; } public string GetHelloWorld(string name) { return "Hello " + name; } } }
接着,来继续为这个WCF服务提供一个宿主环境,这里先以控制台应用程序来实现宿主应用程序,具体的实现代码和配置代码如下所示:
namespace WCFServiceHostByConsoleApp { class Program { static void Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(Services.HelloWorldService))) { host.Opened += delegate { Console.WriteLine("服务已开启,按任意键继续...."); }; host.Open(); Console.ReadLine(); } } } }
对应的服务端配置文件如下所示:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="HelloWorldSerBehavior"> <serviceMetadata httpGetEnabled="True" httpGetUrl="http://localhost:9999/GetHelloWorldService"/> </behavior> </serviceBehaviors> </behaviors> <services> <service name ="Services.HelloWorldService" behaviorConfiguration="HelloWorldSerBehavior"> <endpoint address="http://localhost:9999/GetHelloWorldService" binding="basicHttpBinding" contract="Contract.IHelloWorld"/> </service> </services> </system.serviceModel> </configuration>
接着,我们来创建一个客户端通过代理对象来调用WCF服务方法。首先以管理员运行WCFServiceHostByConsoleApp.exe文件来开启服务,WCF服务开启成功后,在对应的客户端右键添加服务引用,在打开的添加服务引用窗口中输入WCF服务地址:http://localhost:9999/GetHelloWorldService,点确定按钮来添加服务引用,添加成功后,VS中集成的代码生成工具会帮我们生成对应的代理类。接下来,我们可以通过创建一个代理对象来对WCF进行访问。具体客户端的实现代码如下所示:
1 namespace Client3 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 using (HellworldServiceClient helloWorldProxy = new HellworldServiceClient()) 8 { 9 Console.WriteLine("服务返回的结果是: {0}", helloWorldProxy.GetHelloWorldWithoutParam()); 10 Console.WriteLine("服务返回的结果是: {0}", helloWorldProxy.GetHelloWorldWithParam("Learning Hard")); 11 } 12 13 Console.ReadLine(); 14 } 15 } 16 }
这样,你运行客户端程序时(注意不要关闭WCF服务宿主程序),你将看到如下图所示的运行结果。
在上面客户端的实现代码中,从客户端的角度来看,我们并不知道我们是对重载方法进行调用,因为我们调用的明明是两个不同的方法名,这显然还不是我们最终想要达到的效果,此时,有两种方式来达到客户端通过相同方法名来调用。
- 第一种方式就是手动修改生成的服务代理类和服务契约代码,使其支持操作重载,修改后的服务代理和服务契约代码如下所示:
namespace Client3.ServiceReference { [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ServiceModel.ServiceContractAttribute(Namespace="http://www.Learninghard.com", ConfigurationName="ServiceReference.HellworldService")] public interface HellworldService { // 把自动生成的方法名GetHelloWorldWithoutParam修改成GetHelloWorld [System.ServiceModel.OperationContractAttribute(Name = "GetHelloWorldWithoutParam", Action = "http://www.Learninghard.com/HellworldService/GetHelloWorldWithoutParam", ReplyAction = "http://www.Learninghard.com/HellworldService/GetHelloWorldWithoutParamResponse")] string GetHelloWorld(); // // 把自动生成的方法名GetHelloWorldWithoutParamAsync修改成GetHelloWorldAsync [System.ServiceModel.OperationContractAttribute(Name = "GetHelloWorldWithoutParam", Action="http://www.Learninghard.com/HellworldService/GetHelloWorldWithoutParam", ReplyAction="http://www.Learninghard.com/HellworldService/GetHelloWorldWithoutParamResponse")] System.Threading.Tasks.Task<string> GetHelloWorldAsync(); [System.ServiceModel.OperationContractAttribute(Name = "GetHelloWorldWithParam", Action="http://www.Learninghard.com/HellworldService/GetHelloWorldWithParam", ReplyAction="http://www.Learninghard.com/HellworldService/GetHelloWorldWithParamResponse")] string GetHelloWorld(string name); [System.ServiceModel.OperationContractAttribute(Name = "GetHelloWorldWithParam", Action = "http://www.Learninghard.com/HellworldService/GetHelloWorldWithParam", ReplyAction = "http://www.Learninghard.com/HellworldService/GetHelloWorldWithParamResponse")] System.Threading.Tasks.Task<string> GetHelloWorldAsync(string name); } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public interface HellworldServiceChannel : Client3.ServiceReference.HellworldService, System.ServiceModel.IClientChannel { } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public partial class HellworldServiceClient : System.ServiceModel.ClientBase<Client3.ServiceReference.HellworldService>, Client3.ServiceReference.HellworldService { public HellworldServiceClient() { } public HellworldServiceClient(string endpointConfigurationName) : base(endpointConfigurationName) { } public HellworldServiceClient(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public HellworldServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public HellworldServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : base(binding, remoteAddress) { } public string GetHelloWorld() { return base.Channel.GetHelloWorld(); } public System.Threading.Tasks.Task<string> GetHelloWorldAsync() { return base.Channel.GetHelloWorldAsync(); } public string GetHelloWorld(string name) { return base.Channel.GetHelloWorld(name); } public System.Threading.Tasks.Task<string> GetHelloWorldAsync(string name) { return base.Channel.GetHelloWorldAsync(name); } } }