c# – MVC3 REST路由和Http动词
发布时间:2020-12-15 03:44:16 所属栏目:百科 来源:网络整理
导读:作为我的 previous question的一个结果,我发现了在MVC3中处理REST路由的两种方式. 这是一个后续问题,我正在尝试学习这两种方法之间的事实差异/微妙之处.如果可能,我正在寻求权威的答案. 方法1:单路由,操作名称Http控制器动作的动态属性 使用指定的动作参数
作为我的
previous question的一个结果,我发现了在MVC3中处理REST路由的两种方式.
这是一个后续问题,我正在尝试学习这两种方法之间的事实差异/微妙之处.如果可能,我正在寻求权威的答案. 方法1:单路由,操作名称Http控制器动作的动态属性 >使用指定的动作参数在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);); } 方法2:唯一路由动词约束,控制器动作具有Http动词属性 >使用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路由…但是限制路由与使用代理操作名称有什么不同? 解决方法
你不会得到一个权威的答案,这里是我的2美分:
我更喜欢方法2,因为那里你有一个地方的所有路由.您可以将路由封装成一个方法,例如MapResourceRoutes(字符串控制器,字符串uri),并在整个API中使用了多个时间. 另外,方法2给出了可以用于链接和反向路由的清晰命名的路由. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |