Como resultado de un previous question mío, he descubierto dos formas de manejar rutas REST en MVC3.MVC3 REST Rutas y verbos Http
Esta es una pregunta de seguimiento en la que trato de aprender las diferencias/sutilezas entre estos dos enfoques. Estoy buscando una respuesta autorizada si es posible.
Método 1: Ruta individual, con el nombre Acción + Http verbal atributos en acciones del controlador
Register una sola ruta en
Global.asax
usando unaction
parámetro especificado.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" }); }
se aplican tanto
ActionName
yHttpVerb
atribuye a acciones de controladores[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);); }
Método 2: Rutas únicos + Limitaciones del verbo, con Http verbo atributo en las acciones del controlador
Registro rutas únicas en
Global.asax
conHttpMethodContraint
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") });
Use sólo un HTTP verbo atributo en las acciones del controlador
[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);); }
Ambos métodos me dejó tener un nombre único Métodos acción del controlador, y permitir rutas RESTful vinculadas a los verbos ... pero ¿qué es inherentemente diferente sobre la restricción de la ruta frente a usar un nombre de acción de proxy?