【问题标题】:Can WCF Restful service allow same method expose as WebGet and WebInvoke?WCF Restful 服务可以允许与 WebGet 和 WebInvoke 相同的方法公开吗?
【发布时间】:2014-06-02 22:31:18
【问题描述】:

WCF Restful 服务能否允许与 WebGet 和 WebInvoke 类似的方法重载一样公开相同的方法?两种方法都应该可以从同一个 URL 访问。

例如

 [ServiceContract]
public interface IWeChatBOService
{

    [WebGet(UriTemplate = "WeChatService/{username}")]
    [OperationContract]
    string ProcessRequest(string MsgBody);

    [WebInvoke(Method = "POST", UriTemplate = "WeChatService/{username}")]
    [OperationContract]
    string ProcessRequest(string MsgBody);

WCF Restful Service 可以吗?

【问题讨论】:

  • 不可能重载,但您可以尝试将另一个名称命名为 ProccessRequestPost 并保持 UriTemplate 相同。我不知道它是否有效,只是一个建议。

标签: c# .net wcf wcf-rest


【解决方案1】:

是的,这是可能的,但需要稍作改动。 您只需要更改方法的名称,但您可以对这两个端点使用相同的 url。例如,您可以执行以下操作:

[OperationContract]
[WebGet(UriTemplate = "GetData/{value}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Xml)]
        string GetData2(string value);

[OperationContract]
[WebInvoke(UriTemplate = "GetData/{value}", RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Xml)]
        string GetData(string value);

首先只能通过 GET 请求访问,其次只能通过 POST 方法访问。

【讨论】:

    【解决方案2】:

    是的,这是可能的,Tequila 的回答非常接近预期:

    [ServiceContract]
    public interface IWeChatBOService
    {
    
        [WebGet(UriTemplate = "WeChatService/{msgBody}")]
        [OperationContract]
        string ProcessRequest(string msgBody);
    
        [WebInvoke(Method = "POST", UriTemplate = "WeChatService")]
        [OperationContract]
        string ProcessRequest2(string msgBody);
    }
    

    但我不建议设计这样的 api。最好在 enpoint 描述中描述 base uri,UriTemplate 应该反映资源标识符:

    [ServiceContract]
    public interface IWeChatBOService
    {
    
        [WebGet(UriTemplate = "messages/{messageId}")]
        [OperationContract]
        string GetMessage(string messageId);
    
        [WebInvoke(Method = "POST", UriTemplate = "messages")]
        [OperationContract]
        string InsertMessage(string message);
    }
    

    这是一个很好的建议:

    REST Best practices

    RESTful API Design

    【讨论】:

      【解决方案3】:

      或者我们可以为重载方法使用别名。在这种情况下,我们可以使用这些别名(不是原始名称)访问此操作:

      [ServiceContract]
      interface IMyCalculator
      {
          //Providing alias AddInt, to avoid naming conflict at Service Reference
          [OperationContract(Name = "AddInt")]
          public int Add(int numOne, int numTwo);
      
          //Providing alias AddDobule, to avoid naming conflict at Service Reference
          [OperationContract(Name = "AddDouble")]
          public double Add(int numOne, double numTwo); 
      }
      

      在上面的例子中,这些方法可以在客户端使用它们的别名来访问;分别是 AddInt 和 AddDouble。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-06
        • 2012-07-10
        • 2011-09-02
        • 2011-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多