C# ASP.NET WebApi - 一个控制器中的多个 GET 操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17511844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:41:52  来源:igfitidea点击:

ASP.NET WebApi - Multiple GET actions in one controller

c#asp.netasp.net-mvc-4asp.net-web-api

提问by Stan

I have Userscontroller and basic REST pattern is working just fine. However I need one additional pattern users/{id}/usergroupsthat will return all user groups for that user.

我有Users控制器,基本的 REST 模式工作得很好。但是我需要一个额外的模式users/{id}/usergroups来返回该用户的所有用户组。

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...

实现这一点的最佳方法是什么,因为我想我将需要在更多控制器上使用类似的路由。仅仅默认是不够的......

Error

错误

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

找到多个与请求匹配的操作: Api.Models.Users.User GetUser(Int32) on type Api.Controllers.UsersController System.Collections.Generic.IEnumerable`1[Api.Models.Users.UserGroup] GetUserGroups(Int32) on输入 Api.Controllers.UsersController

Code

代码

// 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

Edit 1

编辑 1

I did what amhedsuggested and it doesn't solve the issue.

我做了amhed的建议,但没有解决问题。

// 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 }
);

采纳答案by amhed

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

您可以:只定义一个Get方法,并有一个可选的 Id 参数,如下所示:

public IEnumerable<User> 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

或者您可以使用 ActionName 属性装饰多个 Gets

// 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

And then define the routes on your RouteConfig like so:

然后在您的 RouteConfig 上定义路由,如下所示:

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

回答by Vince Cipriani

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).

我一直在使用 Web API v1,并提出了以下解决方案。对于所有常规路由,将 ActionName 声明为“默认”。然后在您的路由配置中,设置默认操作 =“默认”。这会将您对 /Users/5 的调用更改为 users/5/default 并确保它映射到正确的位置。我发现这个解决方案的唯一问题是文档将显示路由的 /Default 部分。看起来您可以像这个人一样编辑您的视图以排除这些(https://stackoverflow.com/a/29353198/4374666)。

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

如果您使用的是 v2,似乎属性路由将是最干净的方式。

// 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<UserGroup> GetUserGroups(int id) // THIS WORKS

// ROUTES
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}/{action}",
    defaults: new { id = RouteParameter.Optional,
 action = "Default" }
);