WCF的实际应用方法多样化,要想全部掌握是一件非常困难的事情。不过我们可以在不断的实践中去积累应用经验,以帮助我们提高熟练应用程度。在这里就可以先学到一个WCF openation的应技巧。
很多时候我们用到方法的重载,在WCF中也不例外.不过需要加一点东西.我们以正常的方法来写一个方法的重载,代码如下:
- [ServiceContract]
- public interface ICalculatorContract
- {
- [OperationContract]
- int add(int x, int y);
- [OperationContract]
- double add(double x, double y);
- }
我把add方法进行了重载.
- public class CalculatorService:ICalculatorContract
- {
- #region ICalculatorContract Members
- int ICalculatorContract.add(int x, int y)
- {
- return x + y;
- }
- #endregion
- #region ICalculatorContract Members
- public double add(double x, double y)
- {
- return x + y;
- }
- #endregion
- }
host 如下:
- BasicHttpBinding binding = new BasicHttpBinding();
- Uri baseUri=new Uri ("http://172.28.3.45/CalculatorService");
- ServiceHost host = new ServiceHost(typeof(CalculatorService), baseUri);
- host.AddServiceEndpoint(typeof(ICalculatorContract),
binding,string.Empty);- ServiceMetadataBehavior behavior = host.Description.Behaviors.
Find<ServiceMetadataBehavior>();- if (behavior == null)
- {
- behavior = new ServiceMetadataBehavior();
- behavior.HttpGetEnabled = true;
- behavior.HttpGetUrl = baseUri;
- host.Description.Behaviors.Add(behavior);
- }
- host.Open();
这时我们运行host会出现异常:
Cannot have two operations in the same contract with the same name, methods add and add in type CalculatorContract.ICalculatorContract violate this rule. You can change the name of one of the operations by changing the method name or by using the Name property of OperationContractAttribute.
出现这个异常的原因是因为soap message action,不能区分这两个方法:所以解决如下:
- [ServiceContract]
- public interface ICalculatorContract
- {
- [OperationContract(Name="add1")]
- int add(int x, int y);
- [OperationContract(Name="add2")]
- double add(double x, double y);
- }
为WCF openation加一个***的name值.这样不可以soap message区分这两个方法了.再次运行host.没有异常了.
这样客户端就可以正常使用add方法.
【编辑推荐】