很多时候我们用到方法的重载,在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);

    } 

为openation加一个唯一的name值.这样不可以soap message区分这两个方法了.再次运行host.没有异常了.

这样客户端就可以正常使用add方法.

 

 

posted on 2008-11-21 11:54  John.Lau  阅读(284)  评论(0编辑  收藏  举报