ASP.NET WebApi - Multiple GET actions in one controller

后端 未结 2 1912
忘了有多久
忘了有多久 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 09:09

    You can either: just define one Get method, and have an optional Id Parameter like this:

    public IEnumerable GetUsers(int? id){
        if (id.HasValue)
        {
             //return collection of one item here
        }
        //return collection of all items here
    }
    

    Or you can have multiple Gets decorated with the ActionName Attribute

    // GET api/Users
    [ActionName("GetAll")]
    public IEnumerable GetUsers()
    
    // GET api/Users/5
    [ActionName("Get")]
    public User GetUser(int id) // THIS IS NO LONGER IN CONFLICT
    

    And then define the routes on your RouteConfig like so:

    routes.MapHttpRoute(
                name: "DefaultApiWithAction",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
    

提交回复
热议问题