路由模板不适用于 FromQuery 属性
Route Template not working with FromQuery attribute
我正在使用下面的路由,它工作正常-
[HttpGet("{id}/{category}")]
public ActionResult<Pet> GetById(int id, string category, [FromQuery] string position)
ID = 1000、类别 =“本地”和位置 =“中间”的记录的 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 错误。 url 看起来像 -
https://localhost:12345/api/v1/Pets/1000?category=Native&position=Mid
任何人都可以帮助我理解我在这里做错了什么吗?为什么它使用简单的 fromQuery 参数而不是倍数?
如果问题是您有两条相互冲突的路由,每条路由都需要不同的参数类型(即,一个需要字符串,另一个需要整数),向其中一个添加路由约束将会解决这个问题。最简单的方法是将“: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"
};;
}
}
我正在使用下面的路由,它工作正常-
[HttpGet("{id}/{category}")]
public ActionResult<Pet> GetById(int id, string category, [FromQuery] string position)
ID = 1000、类别 =“本地”和位置 =“中间”的记录的 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 错误。 url 看起来像 - https://localhost:12345/api/v1/Pets/1000?category=Native&position=Mid
任何人都可以帮助我理解我在这里做错了什么吗?为什么它使用简单的 fromQuery 参数而不是倍数?
如果问题是您有两条相互冲突的路由,每条路由都需要不同的参数类型(即,一个需要字符串,另一个需要整数),向其中一个添加路由约束将会解决这个问题。最简单的方法是将“: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"
};;
}
}