I'm building an API for a Twitter like site using Web API and have trouble with mapping the routes
I have the following actions for the User controller:
public User Get(string firstname, string lastname)
public User Get(Guid id)
public User Friends(Guid id)
public User Followers(Guid id)
public User Favorites(Guid id)
The desired routes and the generated documentation should be:
api/users?firstname={firstname}&lastname={lastname}
api/users/{id}
api/users/{id}/friends
api/users/{id}/followers
api/users/{id}/favorites
In WebApiConfig.cs I have:
config.Routes.MapHttpRoute(
"2",
"api/{controller}/{id}",
new { action = "get", id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
"1",
"api/{controller}/{id}/{action}"
);
How can I map WebAPI routes correctly?
Routing is order sensitive. The first match always wins. So it is important that you order you routes from most-specific to least-specific.
When your routes are ordered this way, you will get the behavior you expect.
Given the flexibility you want you should take a look at
Attribute Routing in ASP.NET Web API 2
In WebApiConfig.cs enable attribute routing like
In UserController
Note given the names of actions
Friends, Followers and Favorites
they imply returning collections rather than single userThere are a variety of useful reference materials on this subject, such as:
Have you had a look at these?
Update..
Its better practise to explicitly state which parameter is which, ie:
Main thing I could see wrong was you had action / id in the wrong order in route "1".