简体   繁体   English

如何在ASP.NET中的同一路由上使用多个GET方法?

[英]How do I use multiple GET methods on the same route in ASP.NET?

Suppose I have a resource in ASP.NET like so: 假设我在ASP.NET中有这样的资源:

/api/cars

and I want to expose information about cars for sale. 我想公开有关待售汽车的信息。 I want to expose it in two ways: 我想以两种方式公开它:

/api/cars?model=camry

/api/cars?make=toyota

I can implement the search for one of them, but not both at the same time since their signatures are identical. 我可以实现对其中之一的搜索,但不能同时搜索两者,因为它们的签名是相同的。 I'm using an ApiController in .NET 4.5: how can I implement both searches on the same resource? 我在.NET 4.5中使用ApiController:如何在同一个资源上实现两个搜索?

You can use nullable input parameters. 您可以使用可为空的输入参数。 Since you are using strings, you don't even have to declare them as nullable. 由于您使用的是字符串,因此您甚至不必将它们声明为可为空。 See this SO article. 请参阅此SO文章。 The gist is 要点是

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

    if(!string.IsNullOrEmpty(make))
    {
        // do something with make
    }
}

As described in the linked SO article, any of the following routes will direct you to the right action: 如链接的SO文章中所述,以下任何路由都将引导您采取正确的措施:

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

Here is another good SO article on the subject. 是关于该主题的另一篇很好的SO文章。

I'm assuming that you are using WebApi (eg your ApiController is System.Web.Http.ApiController ) 我假设您正在使用WebApi(例如,您的ApiControllerSystem.Web.Http.ApiController

Then your controller method will simply be 然后,您的控制器方法就是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM