如何在WCF中使用两个具有相同名称的方法?

Sag*_*gar 6 .net c# wcf

可能重复:
为什么你不能在WCF中重载一个方法?

我正在开发一个使用WCF服务的项目.我的问题是,在wcf服务中我有一个名为"Display()"的方法,我使用client1.现在我想添加另一个具有相同名称但有一个参数的方法,即."显示(字符串名称)",以便新的clinet2可以使用新方法,旧的client1可以使用旧方法.我怎样才能做到这一点.这是我写的代码.提前10Q.

namespace ContractVersioningService
{
  [ServiceContract]
  public interface IService1 
  {
    [OperationContract]
    string Display();

    [OperationContract]
    string GoodNight();
  }     
}

namespace ContractVersioningService
{
   public class Service1 : IService1
   {
     public string Display()
     {
        return "Good Morning";          
     }

     public string GoodNight()
     {
        return "Good Night";
     }
   }
}    

namespace ContractVersioningService
{
  [ServiceContract(Namespace = "ContractVersioningService/01", Name =      "ServiceVersioning")]
  public interface IService2 : IService1
  {
     [OperationContract]
     string Disp(string greet);
  }
}

namespace ContractVersioningService
{

   public class Service2 : Service1, IService2
   {
      public string Display(string name)
      {
         return name;
      }

      public string Disp(string s)
      {
         return s;
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

C-v*_*-va 12

    Why WCF doesnot support method overloading directly ?
Run Code Online (Sandbox Code Playgroud)
  • 因为WSDL不支持方法重载(不是OOP).WCF生成WSDL,它指定服务的位置以及服务公开的操作.

    WCF使用Document/Literal WSDL样式:Microsoft提出了这个标准,其中soap body元素将包含Web方法名称.

  • 默认情况下,所有WCF服务都符合文档文字标准,其中soap正文应包含方法名称.

    唯一的方法是使用Name属性.例如,

        [OperationContract(Name="Integers")]
        int Display(int a,int b)
        [OperationContract(Name="Doubles")]
        double Display(double a,double b)
    
    Run Code Online (Sandbox Code Playgroud)

编译器将生成以下内容,这对于wsdl定位是有意义的

     [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    [System.ServiceModel.ServiceContractAttribute(ConfigurationName=
    "ServiceRef.IService1")]
  public interface IService1
   {
       [System.ServiceModel.OperationContractAttribute(
       Action="http://tempuri.org/Service1/AddNumber",
       ReplyAction="http://tempuri.org/IHelloWorld/IntegersResponse")]                   
       int Display(int a,int b)

       [System.ServiceModel.OperationContractAttribute(
       Action="http://tempuri.org/IHelloWorld/ConcatenateStrings",
       ReplyAction="http://tempuri.org/Service1/DoublesResponse")]
       double Display(double a,double b)
  }
Run Code Online (Sandbox Code Playgroud)


Chr*_*n.K 7

好的,我打算回答这个问题,因为现在评论过多了.

你基本上有两个选择:

  • 使用单个接口(请注意,接口继承,就像您在问题中建议的那样,在技术上统计为一个接口),但是您必须为每个服务操作指定一个不同的名称.您可以通过命名C#方法distinct或通过应用[OperationContract(Name = "distinctname")]属性来实现.

  • 使用两个单独的接口,它们之间没有任何继承关系,在不同的端点上发布每个接口.然后,您可以在每个服务操作中使用相同的名称,但具有不同的参数.如果您愿意/需要,您仍然可以使用一个实现类实现这两个接口.