我正在使用以下路由并且它工作正常-
[HttpGet("{id}/{category}")]
public ActionResult<Pet> GetById(int id, string category, [FromQuery] string position)
id = 1000、category = "Native" 和 position = "Mid" 的记录的 URL 看起来像 - https://localhost:12345/api/v1/Pets/1000/Native?position=mid>
现在我想让 Category 参数也作为 FromQuery 获取。我正在尝试进行如下更改
[HttpGet("{id}")]
public ActionResult<Pet> GetById(int id, [FromQuery]string category, [FromQuery] string position)
但它不起作用并给出 500 错误。网址看起来像 - https://localhost:12345/api/v1/Pets/1000?category=Native&position=Mid
谁能帮我理解我在这里做错了什么?为什么它使用简单的 fromQuery 参数而不是倍数?
答案 0 :(得分:1)
如果问题是您有两条相互冲突的路由,每条路由都需要不同的参数类型(即,一个需要字符串,另一个需要整数),则向其中一个添加路由约束将解决问题问题。最简单的方法是将 ":int" 添加到您在此处发布的操作方法中,正如@monty 在评论中建议的那样。下面是一个工作示例
[Route("api/v1/pets")]
public class PetsController : ControllerBase
{
[HttpGet("{name}")]
public ActionResult<Pet> GetByName(string name, [FromQuery]string category, [FromQuery] string position)
{
return new Pet()
{
Name = "Cat"
};;
}
[HttpGet("{id:int}")]
public ActionResult<Pet> GetById(int id, [FromQuery]string category, [FromQuery] string position)
{
return new Pet()
{
Name = "Dog"
};;
}
}