ASP.NET WebApi-一个控制器中的多个GET操作 [英] ASP.NET WebApi - Multiple GET actions in one controller
问题描述
我有Users
控制器,基本的REST模式工作正常.但是,我需要一个额外的模式users/{id}/usergroups
,它将返回该用户的所有用户组.
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 user groups for that user.
实现此目标的最佳方法是什么,因为我想我将在更多的控制器上需要类似的路由.仅仅默认值是不够的...
What would be the best way to implement this since I imagine I will need similar routes on many more controllers. Just default ones are not enough...
找到了多个与请求相符的动作: 类型为Api.Controllers.UsersController的Api.Models.Users.User GetUser(Int32) System.Collections.Generic.IEnumerable`1 [Api.Models.Users.UserGroup] GetUserGroups(Int32),类型为Api.Controllers.UsersController
Multiple actions were found that match the request: Api.Models.Users.User GetUser(Int32) on type Api.Controllers.UsersController System.Collections.Generic.IEnumerable`1[Api.Models.Users.UserGroup] GetUserGroups(Int32) on type Api.Controllers.UsersController
代码
// GET api/Users
public IEnumerable<User> GetUsers()
// GET api/Users/5
public User GetUser(int id) // THIS IS CONFLICT 1
// PUT api/Users/5
public HttpResponseMessage PutUser(int id, User user)
// POST api/Users
public HttpResponseMessage PostUser(User user)
// DELETE api/Users/5
public HttpResponseMessage DeleteUser(int id)
// GET api/Users/5/UserGroups
public IEnumerable<UserGroup> GetUserGroups(int id) // THIS IS CONFLICT 2
编辑1
我做了建议 ,但并不能解决问题.
Edit 1
I did what amhed suggested and it doesn't solve the issue.
// GET api/Users/5
[HttpGet, ActionName("getuser")]
public User GetUser(int id) // THIS STILL DOES NOT WORK
// GET api/Users/5/UserGroups
[HttpGet, ActionName("usergroups")]
public IEnumerable<UserGroup> GetUserGroups(int id) // THIS WORKS
// ROUTES
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}/{action}",
defaults: new { id = RouteParameter.Optional, action = RouteParameter.Optional }
);
推荐答案
您可以:仅定义一个Get
方法,并具有如下所示的可选ID参数:
You can either: just define one Get
method, and have an optional Id Parameter like this:
public IEnumerable<User> GetUsers(int? id){
if (id.HasValue)
{
//return collection of one item here
}
//return collection of all items here
}
或者您可以使用ActionName属性装饰多个Gets
Or you can have multiple Gets decorated with the ActionName Attribute
// GET api/Users
[ActionName("GetAll")]
public IEnumerable<User> GetUsers()
// GET api/Users/5
[ActionName("Get")]
public User GetUser(int id) // THIS IS NO LONGER IN CONFLICT
然后在RouteConfig上定义路由,如下所示:
And then define the routes on your RouteConfig like so:
routes.MapHttpRoute(
name: "DefaultApiWithAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
这篇关于ASP.NET WebApi-一个控制器中的多个GET操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!