Kết quả là previous question của tôi, tôi đã phát hiện ra hai cách xử lý các tuyến REST trong MVC3.MVC3 REST Route & Http Verbs
Đây là câu hỏi tiếp theo mà tôi đang cố gắng tìm hiểu sự khác biệt thực tế/sự tinh tế giữa hai cách tiếp cận này. Tôi đang tìm kiếm câu trả lời có thẩm quyền nếu có thể.
Phương pháp 1: Độc thân Route, với hành động Tên + Http Động từ thuộc tính trên điều khiển Actions
Đăng ký một tuyến đường duy nhất trong
Global.asax
sử dụng một quy địnhaction
tham số.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" }); }
Áp dụng cả
ActionName
vàHttpVerb
thuộc tính để điều khiển hành động[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);); }
Phương pháp 2: Các tuyến đường độc đáo + Hạn chế Verb, với Http Động từ thuộc tính trên điều khiển Actions
ký các tuyến đường duy nhất trong
Global.asax
vớiHttpMethodContraint
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") });
Chỉ sử dụng một Http Động từ thuộc tính trên Actions khiển
[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);); }
Cả hai phương pháp cho tôi đã được đặt tên duy nhất điều khiển phương pháp hành động, và cho phép các tuyến đường RESTful được gắn với các động từ ... nhưng những gì vốn đã khác nhau về việc hạn chế tuyến đường so với sử dụng tên hành động proxy?