这是一个后续问题,我正在尝试学习这两种方法之间的事实差异/微妙之处.如果可能,我正在寻求权威的答案.
方法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给出了可以用于链接和反向路由的清晰命名的路由.
总结以上是内存溢出为你收集整理的c# – MVC3 REST路由和Http动词全部内容,希望文章能够帮你解决c# – MVC3 REST路由和Http动词所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)