How to make the correct route for {id} / visit?

I am new to asp.core, so I try to make the correct route to {id}/visits

My code is:

[Produces("application/json")]
[Route("/Users")]
public class UserController 
{
    [HttpGet]
    [Route("{id}/visits")]
    public async Task<IActionResult> GetUser([FromRoute] long id)
    {
        throw new NotImplementedException()
    }
}

But, with the route, the {id}generated method is the same:

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

How to make a /Users/5/visitsnethod route ?
What options GetUsershould I add?

+4
source share
1 answer

Name the methods differently and use constraints to avoid route conflicts:

[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
    }
}
+5
source

Source: https://habr.com/ru/post/1683703/


All Articles