C# &引用;GetBy";webapi中的方法
我们正在使用.NETCore构建一个Web API。我们需要支持“GetBy”功能,例如GetByName、GetByType等。但我们遇到的问题是如何通过Restful方式描述这一点,以及方法重载不能正确处理我们认为应该如何处理路由。我们正在使用MongoDB,所以我们的ID是字符串 我假设我们的路线应该是这样的:C# &引用;GetBy";webapi中的方法,c#,rest,asp.net-web-api,asp.net-core,C#,Rest,Asp.net Web Api,Asp.net Core,我们正在使用.NETCore构建一个Web API。我们需要支持“GetBy”功能,例如GetByName、GetByType等。但我们遇到的问题是如何通过Restful方式描述这一点,以及方法重载不能正确处理我们认为应该如何处理路由。我们正在使用MongoDB,所以我们的ID是字符串 我假设我们的路线应该是这样的: /api/templates?id=1 /api/templates?name=ScienceProject /api/templates?type=Project 问题是控制器
/api/templates?id=1
/api/templates?name=ScienceProject
/api/templates?type=Project
问题是控制器中的所有方法都只有一个字符串参数,并且没有正确映射。路由是否应该不同,或者是否有方法将这些路由正确映射到正确的方法?您可以使用一个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);
}
}
如果参数是互斥的,即只按名称或类型搜索,而不按名称和类型搜索,则可以将参数作为路径的一部分,而不是查询参数 范例
[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
如果这些参数不是相互排斥的,那么您应该按照