c# – 如何为{id} /访问制作有效路线?
作者:互联网
我是asp.core的新手,所以我尝试制作{id} / visits的有效路线
我的代码:
[Produces("application/json")]
[Route("/Users")]
public class UserController
{
[HttpGet]
[Route("{id}/visits")]
public async Task<IActionResult> GetUser([FromRoute] long id)
{
throw new NotImplementedException()
}
}
但是,在路由{id}生成的方法相同:
// GET: /Users/5
[HttpGet("{id}")]
public async Task<IActionResult> GetUser([FromRoute] long id)
{
return Ok(user);
}
如何制作路线/用户/ 5 /访问nethod?
我应该添加GetUser的哪些参数?
解决方法:
以不同方式命名方法并使用约束来避免路由冲突:
[Produces("application/json")]
[RoutePrefix("Users")] // different attribute here and not starting /slash
public class UserController
{
// Gets a specific user
[HttpGet]
[Route("{id:long}")] // Matches GET Users/5
public async Task<IActionResult> GetUser([FromRoute] long id)
{
// do what needs to be done
}
// Gets all visits from a specific user
[HttpGet]
[Route("{id:long}/visits")] // Matches GET Users/5/visits
public async Task<IActionResult> GetUserVisits([FromRoute] long id) // method name different
{
// do what needs to be done
}
}
标签:c,asp-net-core,asp-net-core-webapi,asp-net-core-routing 来源: https://codeday.me/bug/20190608/1196309.html