由于 previous question我发现了两种在 MVC3 中处理 REST 路由的方法。
这是一个后续问题,我试图了解这两种方法之间的实际差异/微妙之处。如果可能的话,我正在寻找权威的答案。
方法 1:单一路由,在 Controller 操作上使用操作名称 + 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
属性应用于 Controller 操作[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);); }
方法二:Unique Routes + Verb Constraints,Http Verb Attribute on Controller Actions
使用
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") });
在 Controller 操作上只使用一个 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);); }
这两种方法都让我拥有唯一命名的 Controller 操作方法,并允许将 RESTful 路由绑定(bind)到动词...但是限制路由与使用代理操作名称有什么本质上的不同?
最佳答案
这里是我的 2 美分,你不会得到权威的答案:
我更喜欢方法 2,因为这样您就可以将所有路线安排在一个地方。您可以将路由封装到一个方法中,例如MapResourceRoutes(string controller, string uri)
并在整个 API 中多次使用它。
此外,方法 2 还为您提供了明确命名的路由,您可以将其用于链接和反向路由。
关于c# - MVC3 REST 路由和 Http 动词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8721379/