【问题标题】:How do I use multiple GET methods on the same route in ASP.NET?如何在 ASP.NET 中的同一路由上使用多个 GET 方法?
【发布时间】:2015-03-03 21:28:29
【问题描述】:

假设我在 ASP.NET 中有这样的资源:

/api/cars

我想公开有关待售汽车的信息。我想通过两种方式暴露它:

/api/cars?model=camry

/api/cars?make=toyota

我可以实现对其中之一的搜索,但不能同时搜索两者,因为它们的签名相同。我在 .NET 4.5 中使用 ApiController:如何在同一资源上实现两种搜索?

【问题讨论】:

    标签: c# asp.net rest get


    【解决方案1】:

    您可以使用可为空的输入参数。由于您使用的是字符串,因此您甚至不必将它们声明为可为空的。请参阅this SO 文章。要点是

    public ActionResult Action(string model, string make)
    {
        if(!string.IsNullOrEmpty(model))
        {
            // do something with model
        }
    
        if(!string.IsNullOrEmpty(make))
        {
            // do something with make
        }
    }
    

    如链接的 SO 文章中所述,以下任何路线都将引导您采取正确的行动:

    • GET /api/cars
    • GET /api/cars?make=toyota
    • GET /api/cars?model=camry
    • GET /api/cars?make=toyota&model=camry

    Here 是关于该主题的另一篇不错的 SO 文章。

    【讨论】:

      【解决方案2】:

      我假设您正在使用 WebApi(例如,您的 ApiControllerSystem.Web.Http.ApiController

      那么你的控制器方法就是

      public HttpResponseMessage GetCars([FromUri] string make, [FromUri] string model) {
          ... code ...
      }
      

      【讨论】:

        猜你喜欢
        • 2012-09-28
        • 2021-08-06
        • 2020-05-03
        • 2020-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多