2012-01-04 136 views
10

由於我的previous question,我發現了兩種處理MVC3中的REST路由的方法。MVC3 REST路由和HTTP動詞

這是一個後續問題,我試圖瞭解這兩種方法之間的事實差異/微妙之處。如果可能的話,我正在尋找權威的答案。

方法1:單路,用行動名稱+ HTTP謂詞屬性上的控制器操作

  1. 註冊使用指定的action參數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" }); 
    } 
    
  2. 同時適用ActionNameHttpVerb屬性控制器動作

    [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動詞屬性控制器上的操作

  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") }); 
    
  2. 只能使用一個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路由... 但限制路由與使用代理操作名稱有什麼本質不同?

回答

0

我不知道你會找到一個權威的答案,但我會提供我的意見,正如你可以告訴我的觀點,我的意見很重要;-)。我的純粹主義者認爲第一種選擇更純粹,但是我的經驗是像Url.Action()這樣的輔助方法在使用這種方法解決正確的路線時有時會遇到困難,並且我採用了第二種方法,因爲它真的只有因爲api看起來與消費者完全相同。

1

你不會在這裏得到一個權威的答案是我的2美分:

我喜歡的方法2,因爲你在一個地方所有的路由。您可以將路由封裝到一個方法中,例如MapResourceRoutes(string controller, string uri),並讓它在整個API中使用了多次。

此外,方法2還爲您提供了明確命名的路線,您可以使用它們進行鏈接和反向路由。

0

此時,正確答案是使用Web API。