如何为 {id}/visit 创建有效路线?

How to make valid route for {id}/visit?

我是 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);
}

如何创建路由 /Users/5/visits 方法?
我应该在 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
    }
}