Reputation: 4239
I have an ASP .Net Core 1.1 Web Api. In one of my controllers, I'd like two actions:
[HttpGet("{userId:int}")]
public async Task<IActionResult> GetUser([FromRoute] int id)
{
return Ok(_context.User.Where(u.Id == id));
}
[HttpGet("{groupId:int}")]
public async Task<IActionResult> GetUsersInGroup([FromRoute] int groupId)
{
return Ok(_context.User.Where(u.GroupId == groupId));
}
Both actions have the same signature, except for the method name. How can I make it so that I can call upon the one or the other?
Thanks...
Upvotes: 0
Views: 1217
Reputation: 58783
Think about it from the routing component's point of view. What would you do if you receive a URL like /api/users/123
and you have the above actions in a controller?
You have to differentiate them, with e.g. attributes:
[Route("api/users")]
public class UsersController : Controller
{
[HttpGet("{userId:int}")]
public async Task<IActionResult> GetUser([FromRoute] int userId)
{
return Ok(_context.User.Where(u.Id == userId));
}
[HttpGet("group/{groupId:int}")]
public async Task<IActionResult> GetUsersInGroup([FromRoute] int groupId)
{
return Ok(_context.User.Where(u.GroupId == groupId));
}
}
Now they can be accessed with:
/api/users/123
/api/users/group/123
The controller-level Route-attribute sets a common prefix for all routes so you don't need to specify it for all of them.
Then the HttpGet attribute specifies an additional prefix so they are fundamentally different routes.
Upvotes: 1