如何为{id} /访问制作有效路线?

时间:2017-08-14 17:46:03

标签: 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()
    }
}

但是,在路由{id}生成的方法相同:

// GET: /Users/5
[HttpGet("{id}")]
public async Task<IActionResult> GetUser([FromRoute] long id)
{
    return Ok(user);
}

如何制作路线/Users/5/visits nethod?
我应该在GetUser添加哪些参数?

1 个答案:

答案 0 :(得分:5)

以不同方式命名方法,并使用约束来避免路由冲突:

[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
    }
}