user2128702 user2128702 - 2 months ago 17
reST (reStructuredText) Question

How to map different actions to Web API methods that would have same signature

I am trying to create a REST service using Web Api best practices and I came to a situation I don't know how to handle.

Imagine I have groups and inside of each group I have users.

This is how my GroupController looks like:

[RoutePrefix("api/v1/groups")]
public class GroupsController : ApiController
{
[HttpGet]
[Route("{id:int}")]
public IHttpActionResult Get(int id)
{
return Ok();
}

// I also want to add endpoint which fetches all the users inside of group and I'd like to do it like this:
[HttpGet]
[Route("{id:int}/users")]
public IHttpActionResult Get(int id)
{
return Ok();
}
}


As you can see, my second method won't compile since we can not have two methods with the same signature in the same class.

My route template looks like the standart one:

config.Routes.MapHttpRoute(
name: "DefaultRouting",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);


I know that I can add a route which maps also action method name but I was wondering if there's a better way for achieving my goal. I'd like to stick to the best principles for writing RESTful services. As I know, one of the suggestions is to avoid custom action names since this is more common for WCF services.

Answer

Don't mix MapHttpRoute() style routing configuration and attribute-based routing. It's simpler to use one or the other (I prefer attribute-based as it's explicit and allows for clearer class method names).

You also seem to not be calling the method necessary to enable attribute-based routing on your config - config.MapHttpAttributeRoutes().

Finally, I'd rename your methods as follows to ensure there is no clash in the method signatures: GetGroups(int id)and GetUsersForGroup(int id)