【问题标题】:Two Operations with the same name in the Service [duplicate]服务中具有相同名称的两个操作[重复]
【发布时间】:2014-05-19 18:23:24
【问题描述】:

我可以在同一个服务中有两个名称相同(但签名不同)的操作吗?

例子:

[ServiceContract] 
public interface IMyService {
    [OperationContract]
    bool MyOperation(string target);

    [OperationContract]
    bool MyOperation(List<string> targets); }

我真的需要支持不同的签名,因为我有几个团队在使用我的服务,而只有一个团队需要第二个签名(我不希望团队的其他人不得不更改他们的代码)。

有什么想法吗?

【问题讨论】:

  • 不要使用值类型参数,use data contracts。您可以为您的MyOperationRequest 数据合同提供两个属性(string Target 和List&lt;string&gt; Targets)或类似的东西,并检查设置了哪一个。或者尝试仅使用List&lt;string&gt; 并请求至少设置一项。
  • 我知道数据合约,但我正在做代码维护。代码很旧,是由其他团队开发的。我无法更改当前界面以使用数据合同(这会影响其他团队),但需要支持新界面(对于请求它的团队)。我想唯一的办法就是给它起不同的名字。谢谢你的时间:)

标签: web-services wcf


【解决方案1】:

不,您确实不能为合约拥有相同命名的操作,但您可以将它们分隔在两个合约之间:

[ServiceContract]
public interface IMyService
{
    [OperationContract]
    bool MyOperation(string target);
}

[ServiceContract]
public interface IMyServiceV2
{
    [OperationContract]
    bool MyOperation(List<string> targets);
}


[ServiceContract]
public class MyService : IMyService, IMyServiceV2
{
    public bool MyOperation(string target)
    {
        /* your code*/
        return true;
    }

    public bool MyOperation(List<string> targets)
    {
        /* your code*/
        return true;
    }
}

并暴露两个端点:

<services>
  <service name="YourNamespace.MyService ">
    <endpoint
        address="http://localhost:8000/v1"
        binding="webHttpBinding" 
        contract="YourNamespace.IMyService" />

    <endpoint
        address="http://localhost:8000/v2"
        binding="webHttpBinding" 
        contract="YourNamespace.IMyServiceV2" />
  </service>
</services>

或者您可以为 OperationContract 设置 Name 参数,但对于 SOA 服务,它与重命名函数名称的结果相同。

【讨论】:

  • 谢谢。就我而言,这不是一种选择,但对于任何其他情况它都是有效的。
  • @jpaires 您的预期结果是什么?一个端点(一个地址),但是client1可以访问Method1,client2可以访问Method2?
  • 预期结果是一个端点,并且客户端根据给定的一组参数使用 Method(list_of_params_1) 或 Method(list_of_params_2)。这就像一个操作的方法重载。
  • @jpaires 对于您的情况,只能将 Name 属性用于 Operation contract 属性(如 CodeCaster 提供的链接中所述)。因此,SOAP 消息操作名称将替换为您在 Name 属性中设置的操作名称。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多