4

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.

1 Answer 1

7

You should use RouteParameter.Optional (from Web API), not UrlParameter.Optional (from ASP.NET MVC).

Everything will behave as you want then.

More info:

Sign up to request clarification or add additional context in comments.

1 Comment

Absolutely right. My mistake was adding the route mappings in the MVC config section and then moving them later -- I picked up the UrlParameter.Optional and no matter how many times I looked at it I did not notice the difference. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.