ASP.NET MVC Web.Api Routing - 真实世界的例子

Ara*_*and 3 asp.net-mvc asp.net-mvc-routing asp.net-web-api asp.net-web-api-routing

我一直在Web.Api中查看路由并查看表示端点的各种方法.我遇到了Instagrams REST端点.(它有一些可爱的文档)使用Web.Api什么是设置像Instagrams用户端点的情况的路由和控制器的最佳方法?

User Endpoints
GET/users/user-id                  Get basic information about a user.
GET/users/self/feed                See the authenticated user's feed.
GET/users/user-id/media/recent     Get the most recent media published by a user.
GET/users/self/media/liked         See the authenticated user's list of liked media.
GET/users/search                   Search for a user by name.
Run Code Online (Sandbox Code Playgroud)

如果我想在我的应用程序中复制这些端点,我将如何处理它.我只需要一个带有5种方法的控制器"用户",我需要什么样的路由才能将REST调用指向这些方法?

Jos*_*nke 5

我会以不同的方式构建它.

GET/user
GET/user/user-id
GET/user?q=user-name

GET/media
GET/media/user-id
GET/media/user-id?selection=recent
GET/media/user-id?selection=liked

GET/feed
GET/feed/user-id
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以将控制器保留为特定目标,就像保持您的课程单一责任一样.

  • 用户
  • 媒体
  • 饲料

当您使用这种方法时,用户更容易"猜测"路径.而且我认为你可以在没有任何解释的情况下猜出每条路径的作用.对我而言,当我设计API时,这是最重要的.

GET/controller            - always returns a item list
GET/controller/id         - always returns a specific item
GET/controller?q=         - always queries the controller
GET/controller?selection= - always selects a subset from the list off items
Run Code Online (Sandbox Code Playgroud)

当然,这是开放的解释,但它让你了解我将如何解决这个特定的问题,也许还有一些想法可以考虑.另外看看这本伟大的书Apigee - Web Api Designs

http://info.apigee.com/Portals/62317/docs/web%20api.pdf

编辑:

为了制作你命名的路线,我认为你有2个(不太理想)的选择.

  1. 为每个网址映射特定路由
  2. 制作通配符路线

选项1 我没有尝试过,或者自己使用过,但你可以在这里找到更多信息:

ASP.NET Web API中具有多个GET方法的单个控制器

选项2 如果您使用通配符路由,则所有带有其他参数的请求都将路由到您的默认Get()方法.在你得到你必须看看使用ControllerContext.Request.RequestUri.AbsolutePath或类似的参数,并选择你的行动.

config.Routes.MapHttpRoute(
     name: "MyApi",
     routeTemplate: "api/{controller}/{id}/{*wildcard}",
     defaults: new { controller = "index", id = RouteParameter.Optional }
 );
Run Code Online (Sandbox Code Playgroud)