作为我的
previous question的一个结果,我发现了在MVC3中处理REST路由的两种方式.
这是一个后续问题,我正在尝试学习这两种方法之间的事实差异/微妙之处.如果可能,我正在寻求权威的答案.
>使用指定的动作参数在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);); }
>使用HttpMethodContraint在Global.asax中注册唯一的路由
var postsUrl = "api/posts"; routes.MapRoute("posts-get",postsUrl + "/{id}",action = "Get",new { httpMethod = new HttpMethodConstraint("GET") }); routes.MapRoute("posts-create",postsUrl,action = "Create",new { httpMethod = new HttpMethodConstraint("POST") }); routes.MapRoute("posts-update",action = "Update",new { httpMethod = new HttpMethodConstraint("PUT") }); routes.MapRoute("posts-delete",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路由…但是限制路由与使用代理操作名称有什么不同?