如何正确映射WebAPI路由 [英] How to map WebAPI routes correctly
问题描述
我正在使用Web API为类似Twitter的网站构建API,但在映射路线时遇到了麻烦
I'm building an API for a Twitter like site using Web API and have trouble with mapping the routes
我对用户控制器执行以下操作:
I have the following actions for the User controller:
public User Get(string firstname, string lastname)
public User Get(Guid id)
public User Friends(Guid id)
public User Followers(Guid id)
public User Favorites(Guid id)
所需的路线和生成的文档应为:
The desired routes and the generated documentation should be:
api/users?firstname={firstname}&lastname={lastname}
api/users/{id}
api/users/{id}/friends
api/users/{id}/followers
api/users/{id}/favorites
在WebApiConfig.cs中,我有:
In WebApiConfig.cs I have:
config.Routes.MapHttpRoute(
"2",
"api/{controller}/{id}",
new { action = "get", id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
"1",
"api/{controller}/{id}/{action}"
);
如何正确映射WebAPI路由?
How can I map WebAPI routes correctly?
推荐答案
鉴于您想要的灵活性,您应该看看
Given the flexibility you want you should take a look at
In WebApiConfig.cs enable attribute routing like
// Web API routes
config.MapHttpAttributeRoutes();
在UserController中
In UserController
注意,因为操作名称Friends, Followers and Favorites
暗示返回集合而不是单个用户
Note given the names of actions Friends, Followers and Favorites
they imply returning collections rather than single user
[RoutePrefix("api/users")]
public class UserController: ApiController {
//eg: GET api/users?firstname={firstname}&lastname={lastname}
[HttpGet]
[Route("")]
public User Get([FromUri]string firstname,[FromUri] string lastname) {...}
//eg: GET api/users/{id}
[HttpGet]
[Route("{id:guid}")]
public User Get(Guid id){...}
//eg: GET api/users/{id}/friends
[HttpGet]
[Route("{id:guid}/friends")]
public IEnumerable<User> Friends(Guid id){...}
//eg: GET api/users/{id}/followers
[HttpGet]
[Route("{id:guid}/followers")]
public IEnumerable<User> Followers(Guid id){...}
//eg: GET api/users/{id}/favorites
[HttpGet]
[Route("{id:guid}/favorites")]
public IEnumerable<User> Favorites(Guid id){...}
}
这篇关于如何正确映射WebAPI路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!