由于我的之前一个问题的结果,我发现在MVC3中处理REST路由有两种方法。
这是一个后续问题,我想了解这两种方法之间的实际差异/细微差别。如果可能,希望得到权威的答案。
方法1:单一路由,使用控制器操作的动作名称+HTTP动词属性
在
Global.asax
中注册一个单一路由,使用指定的action
参数。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););
}
方法二:使用独特的路由+动词约束,在控制器操作中使用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 Verb 属性
[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路由...但是限制路由与使用代理操作名称之间有什么根本区别?