【发布时间】:2012-01-04 02:35:49
【问题描述】:
由于我的previous question,我发现了两种在 MVC3 中处理 REST 路由的方法。
这是一个后续问题,我试图了解这两种方法之间的事实差异/微妙之处。如果可能的话,我正在寻找权威的答案。
方法一:单路由,控制器动作上带有动作名称+Http动词属性
-
使用指定的
action参数在Global.asax中注册单个路由。public override void RegisterArea(AreaRegistrationContext context) { // actions should handle: GET, POST, PUT, DELETE context.MapRoute("Api-SinglePost", "api/posts/{id}", new { controller = "Posts", action = "SinglePost" }); } -
将
ActionName和HttpVerb属性应用于控制器操作[HttpGet] [ActionName("SinglePost")] public JsonResult Get(string id) { return Json(_service.Get(id)); } [HttpDelete] [ActionName("SinglePost")] public JsonResult Delete(string id) { return Json(_service.Delete(id)); } [HttpPost] [ActionName("SinglePost")] public JsonResult Create(Post post) { return Json(_service.Save(post)); } [HttpPut] [ActionName("SinglePost")] public JsonResult Update(Post post) { return Json(_service.Update(post);); }
方法2:唯一路由+动词约束,控制器动作上带有Http动词属性
-
用
HttpMethodContraint在Global.asax注册独特的路线var postsUrl = "api/posts"; routes.MapRoute("posts-get", postsUrl + "/{id}", new { controller = "Posts", action = "Get", new { httpMethod = new HttpMethodConstraint("GET") }); routes.MapRoute("posts-create", postsUrl, new { controller = "Posts", action = "Create", new { httpMethod = new HttpMethodConstraint("POST") }); routes.MapRoute("posts-update", postsUrl, new { controller = "Posts", action = "Update", new { httpMethod = new HttpMethodConstraint("PUT") }); routes.MapRoute("posts-delete", postsUrl + "/{id}", new { controller = "Posts", action = "Delete", new { httpMethod = new HttpMethodConstraint("DELETE") }); -
在控制器动作上仅使用 Http 动词属性
[HttpGet] public JsonResult Get(string id) { return Json(_service.Get(id)); } [HttpDelete] public JsonResult Delete(string id) { return Json(_service.Delete(id)); } [HttpPost] public JsonResult Create(Post post) { return Json(_service.Save(post)); } [HttpPut] public JsonResult Update(Post post) { return Json(_service.Update(post);); }
这两种方法都让我拥有唯一命名的控制器操作方法,并允许绑定到动词的 RESTful 路由...但是限制路由与使用代理操作名称有什么本质上的不同? em>
【问题讨论】:
标签: c# asp.net-mvc http rest routing