문제

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.

도움이 되었습니까?

해결책

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

Everything will behave as you want then.

More info:

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top