MVC3 REST路由和HTTP动词

10

由于我的之前一个问题的结果,我发现在MVC3中处理REST路由有两种方法。

这是一个后续问题,我想了解这两种方法之间的实际差异/细微差别。如果可能,希望得到权威的答案。

方法1:单一路由,使用控制器操作的动作名称+HTTP动词属性

  1. 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" });
    }
    
  2. 在控制器操作上同时应用ActionNameHttpVerb属性

  3. [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动词属性

  1. 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路由...但是限制路由与使用代理操作名称之间有什么根本区别?
    3个回答

    1

    这里可能没有权威的答案,但我有两分钱想法:

    我更喜欢方法2,因为你可以把所有路由都放在一个地方。你可以将你的路由封装成一个方法,例如MapResourceRoutes(string controller, string uri),并在整个API中多次使用它。

    此外,方法2还为你提供了清晰命名的路由,你可以用它们来进行链接和反向路由。


    0

    目前来看,正确的答案是使用Web API。


    0

    我不知道你是否能找到权威的答案,但我会提供我的意见,正如你可以从我的观点中看出来,我的意见很重要。我的纯粹主义者认为第一种选项更加纯粹,然而我的经验是像Url.Action()这样的帮助方法有时候在使用这种方法时会有解析正确路由的问题,因此我采用了第二种方法,因为它在外部看起来与API相同,只有内部实现上有所不同。


    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接