jemerick
jemerick

Reputation: 123

Web API nested routing not working as expected

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 type System.Int32 for method AuthGroup Get(Int64, Int32) in UsersGroupsController. 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

Answers (1)

Filip W
Filip W

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:

Upvotes: 7

Related Questions