【问题标题】:Method overloading in WebAPIWebAPI 中的方法重载
【发布时间】:2015-06-05 05:35:50
【问题描述】:

我正在通过 WebAPI 开发一个 RESTful Web 服务,我需要重载我的一种方法,例如:

[HttpGet]
public void Send(string body, string phoneNumber)

 [HttpGet]
  public void Send(string body, [FromUri] List<string> phoneNumber)

当我使用这个地址调用这个服务时:

http://webservice.com/api/send?body=Hello&phoneNumber=1345456,123123

第一种方法被调用,但我更喜欢使用这个地址来调用第二种方法:

http://webservice.com/api/send?body=Hello&phoneNumber=134556&phoneNumber=123123

但是第一个方法又被调用了!

WebAPI 中的方法可以重载吗?

【问题讨论】:

    标签: c# web-services asp.net-web-api


    【解决方案1】:

    你不能这样做。

    您不能重载(基于参数类型)具有相同路由的 wepapi 操作方法。

    你需要这样做:

    public void Send(string body, [FromUri] List<string> phoneNumber)
    {
        if (string.IsNullOrWhiteSpace(body) || phoneNumber == null)
        {
            // return error message
        }
    
        if (phoneNumber.Count == 1 && phoneNumber[0].IndexOf(',') > -1)
        {
            var phonenumbers = phoneNumber[0]
            .Split(new []{','}, StringSplitOptions.RemoveEmptyEntries);
            // execute method#1 and pass array of phonenumbers
        }
        else
        {
            // execute method#2 and pass list of phonenumbers
        }
    }
    

    【讨论】:

      【解决方案2】:

      一种可能的解决方案是使用 ActionName 属性。一个例子:

      [HttpGet]
      [ActionName("SendWithPhoneNumber")
      public void Send(string body, string phoneNumber)
      
      [HttpGet]
      [ActionName("SendWithPhoneNumbers")
      public void Send(string body, [FromUri] List<string> phoneNumber)
      

      如果您愿意,也可以使用attribute routing。如需更多信息,请查看此thread

      【讨论】:

        猜你喜欢
        • 2016-10-03
        • 2013-03-26
        • 1970-01-01
        • 2021-01-12
        • 2010-09-30
        • 1970-01-01
        • 1970-01-01
        • 2012-09-23
        • 1970-01-01
        相关资源
        最近更新 更多