【问题标题】:"GetBy" Methods in Web APIWeb API 中的“GetBy”方法
【发布时间】:2018-03-23 06:37:34
【问题描述】:
我们正在使用 .NET Core 构建 Web API。我们需要支持“GetBy”功能,例如GetByName、GetByType 等,但我们遇到的问题是如何以 Restful 方式通过路由来描述这一点,以及方法重载与我们认为的路由应该如何工作不正常。我们使用的是 MongoDB,所以我们的 ID 是字符串。
我假设我们的路线应该是这样的:
/api/templates?id=1
/api/templates?name=ScienceProject
/api/templates?type=Project
问题是我们控制器中的所有方法都有一个字符串参数并且没有正确映射。我的路线应该不同还是有办法将这些路线正确映射到正确的方法?
【问题讨论】:
标签:
c#
rest
asp.net-web-api
asp.net-core
【解决方案1】:
如果参数是互斥的,即您只按名称或类型搜索而不是按名称和类型搜索,那么您可以将参数作为路径的一部分而不是查询参数。
例子
[Route("templates")]
public class TemplatesController : Controller
{
[HttpGet("byname/{name}")]
public IActionResult GetByName(string name)
{
return Ok("ByName");
}
[HttpGet("bytype/{type}")]
public IActionResult GetByType(string type)
{
return Ok("ByType");
}
}
这个例子会导致如下路线:
/api/templates/byname/ScienceProject
/api/templates/bytype/Project
如果参数不是互斥的,那么您应该按照answer by Fabian H. 中的建议进行操作
【解决方案2】:
您可以使用单个 get 方法创建一个 TemplatesController,该方法可以获取所有参数。
[Route("api/templates")]
public class TemplatesController : Controller
{
[HttpGet]
public IActionResult Get(int? id = null, string name = null, string type = null)
{
// now handle you db stuff, you can check if your id, name, type is null and handle the query accordingly
return Ok(queryResult);
}
}