由於我的previous question,我發現了兩種處理MVC3中的REST路由的方法。MVC3 REST路由和HTTP動詞
這是一個後續問題,我試圖瞭解這兩種方法之間的事實差異/微妙之處。如果可能的話,我正在尋找權威的答案。
方法1:單路,用行動名稱+ 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動詞屬性控制器上的操作
條
Global.asax
註冊獨特的路線與HttpMethodContraint
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路由... 但限制路由與使用代理操作名稱有什麼本質不同?