WCF operation的重载

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

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值