ASP.NET WebApi - Multiple GET actions in one controller

后端 未结 2 1911
忘了有多久
忘了有多久 2021-02-05 08:20

I have Users controller and basic REST pattern is working just fine. However I need one additional pattern users/{id}/usergroups that will return all u

2条回答
  •  北荒
    北荒 (楼主)
    2021-02-05 08:45

    I'm stuck using Web API v1 and came up w/ the following solution to this. For all of your general routes, declare the ActionName as "Default". Then in your route config, set the default action="Default". This changes your call to /Users/5 to users/5/default and ensures it maps to the right place. The only problem I've found w/ this solution is that the documentation will show the /Default part of the route. It looks like you can edit your view to exclude these as this guy did (https://stackoverflow.com/a/29353198/4374666).

    If you're using v2, it seems like Attribute Routing would be the cleanest way.

    // GET api/Users/5
    [HttpGet, ActionName("Default")]
    public User GetUser(int id) // THIS STILL DOES NOT WORK
    
    // GET api/Users/5/UserGroups
    [HttpGet, ActionName("usergroups")]
    public IEnumerable GetUserGroups(int id) // THIS WORKS
    
    // ROUTES
    config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "{controller}/{id}/{action}",
        defaults: new { id = RouteParameter.Optional,
     action = "Default" }
    );
    

提交回复
热议问题