【发布时间】:2015-03-03 21:28:29
【问题描述】:
假设我在 ASP.NET 中有这样的资源:
/api/cars
我想公开有关待售汽车的信息。我想通过两种方式暴露它:
/api/cars?model=camry
/api/cars?make=toyota
我可以实现对其中之一的搜索,但不能同时搜索两者,因为它们的签名相同。我在 .NET 4.5 中使用 ApiController:如何在同一资源上实现两种搜索?
【问题讨论】:
假设我在 ASP.NET 中有这样的资源:
/api/cars
我想公开有关待售汽车的信息。我想通过两种方式暴露它:
/api/cars?model=camry
/api/cars?make=toyota
我可以实现对其中之一的搜索,但不能同时搜索两者,因为它们的签名相同。我在 .NET 4.5 中使用 ApiController:如何在同一资源上实现两种搜索?
【问题讨论】:
您可以使用可为空的输入参数。由于您使用的是字符串,因此您甚至不必将它们声明为可为空的。请参阅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 文章中所述,以下任何路线都将引导您采取正确的行动:
Here 是关于该主题的另一篇不错的 SO 文章。
【讨论】:
我假设您正在使用 WebApi(例如,您的 ApiController 是 System.Web.Http.ApiController)
那么你的控制器方法就是
public HttpResponseMessage GetCars([FromUri] string make, [FromUri] string model) {
... code ...
}
【讨论】: