我正在使用Web API为类似Twitter的网站构建API,并且无法映射路由
我对用户控制器执行了以下操作:
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)
所需的路线和生成的文件应为:
api/users?firstname={firstname}&lastname={lastname}
api/users/{id}
api/users/{id}/friends
api/users/{id}/followers
api/users/{id}/favorites
在WebApiConfig.cs中我有:
config.Routes.MapHttpRoute(
"2",
"api/{controller}/{id}",
new { action = "get", id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
"1",
"api/{controller}/{id}/{action}"
);
如何正确映射WebAPI路由?
答案 0 :(得分:30)
考虑到你想要的灵活性,你应该看看
Attribute Routing in ASP.NET Web API 2
在WebApiConfig.cs中启用属性路由,如
// Web API routes
config.MapHttpAttributeRoutes();
在UserController中
注意根据操作Friends, Followers and Favorites
的名称,它们意味着返回集合而不是单个用户
[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){...}
}
答案 1 :(得分:4)
路由是对订单敏感的。 第一次匹配总是获胜。因此,您必须订购从最具体到最不具体的路线。
// All parameters are required, or it won't match.
// So it will only match URLs 4 segments in length
// starting with /api.
config.Routes.MapHttpRoute(
"1",
"api/{controller}/{id}/{action}"
);
// Controller is required, id is optional.
// So it will match any URL starting with
// /api that is 2 or 3 segments in length.
config.Routes.MapHttpRoute(
"2",
"api/{controller}/{id}",
new { action = "get", id = RouteParameter.Optional }
);
当您以这种方式订购路线时,您将获得您期望的行为。
答案 2 :(得分:1)
关于此主题有各种有用的参考资料,例如:
你看过这些吗?
<强>更新.. 强>
更好的做法是明确说明哪个参数是哪个,即:
config.Routes.MapHttpRoute(
name: "2",
routeTemplate: "api/{controller}/{id}",
defaults: new { action = "Get", id = RouteParameter.Optional },
);
config.Routes.MapHttpRoute(
name: "1",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: null
);
我可能看错的主要原因是您在路线“1”中的操作/ ID错误。