Adm*_*and 4 c# asp.net-core asp.net-core-webapi asp.net-core-routing
我是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()
}
}
Run Code Online (Sandbox Code Playgroud)
但是,在路由{id}
生成方法上相同:
// GET: /Users/5
[HttpGet("{id}")]
public async Task<IActionResult> GetUser([FromRoute] long id)
{
return Ok(user);
}
Run Code Online (Sandbox Code Playgroud)
如何制作路线/Users/5/visits
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
}
}
Run Code Online (Sandbox Code Playgroud)