Reputation: 123
I am having difficulty with a nested Web API routing set-up.
Given a routing config of:
config.Routes.MapHttpRoute(
name: "UsersGroups",
routeTemplate: "api/users/{userID}/groups/{groupID}",
defaults: new { controller = "UsersGroups", groupID = UrlParameter.Optional }
);
and controller actions like thus:
public AuthGroup Get(long userID, int groupID)
{
//Get specific group here
}
public IEnumerable<AuthGroup> Get(long userID)
{
//get all groups for user here
}
Calling this route /api/users/1528/groups
gives this error:
The parameters dictionary contains a null entry for parameter
groupID
of non-nullable typeSystem.Int32
for methodAuthGroup Get(Int64, Int32)
inUsersGroupsController
. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
I was expecting it to grab the action with the single long parameter, but obviously for some reason it's ignoring this and going straight for the one with most arguments.
Based on what's available at MS on how Web API interprets routes: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection I think what I have should be correct, but obviously it is not working as it seems like it should.
Upvotes: 4
Views: 788
Reputation: 27187
You should use RouteParameter.Optional
(from Web API), not UrlParameter.Optional
(from ASP.NET MVC).
Everything will behave as you want then.
More info:
UrlParameter.Optional
- http://msdn.microsoft.com/en-us/library/system.web.mvc.urlparameter.optional(v=vs.108).aspx
RouteParameter.Optional
- http://msdn.microsoft.com/en-us/library/system.web.http.routeparameter.optional(v=vs.108).aspx
Upvotes: 7