2013-05-14 18 views
3

我使用的是ApiController。我很難理解爲什麼ApiController在某些方面與控制器不同。爲什麼ApiController需要在方法上顯式的Http動詞?

採取

public class QuestionCommentController : ApiController 
{ 
    QuestionCommentCRUD crud = new QuestionCommentCRUD(); 

    // GET api/questioncomment/5 
    [HttpGet] 
    public string Read(int id) 

我習慣於Controller類型的讓我沒有通過屬性指定的法律動詞create方法:

public class QuestionCommentController : Controller 
{ 
    QuestionCommentCRUD crud = new QuestionCommentCRUD(); 

    // GET questioncomment/5 
    public string Read(int id) 

在後一種情況下,我可以執行GET/POST沒有指定HttpGetAttribute。我覺得這種行爲的幾個原因令人困惑:

  • 還有的現在二人HttpGetSystem.Web.Http.HttpGetSystem.Web.Mvc.HttpGet
  • System.Web.Http.HttpGe t的需要,System.Web.Mvc.HttpGet需要GET請求
  • ApiController請求需要唯一途徑/api/controller...

Controller允許我下降int o成功的坑。較新的ApiController需要手持。

我注意到默認模板有語法,我不明白:

public void Post([FromBody]string value) 
    { 
    } 

動詞是一些時髦的[FromBody]事情會沿着方法名。也許這就是爲什麼這樣設置的原因?導致這種設計的ApiController的使用有什麼假設?如果按照建於約定

+0

是因爲它是基於慣例所以你應該調用的行動'GetQuestionComment',並推斷出你創建一個'GET'行動? – theyetiman 2013-05-14 16:34:43

回答

6

你的API控制器不需要的方法動詞。如果您在方法名稱前添加了適當的動詞Get,Post等,則不需要使用該屬性進行修飾。

在你的情況。

public string GetRead(int) 

,並從一個項目中,我目前正在

[Authorize] 
public HttpResponseMessage GetStoreList([FromUri]NamedViewModel model) 

沒有裝修需要,因此不需要System.Web.Http.HttpGet一個活生生的例子。

你可以做到這一點,你有上面列出的方法或我有它的方式。如果您認爲合適,WebApi允許您執行REST或RPC樣式調用。這就是你看到差異的原因。包含對REST風格調用的支持需要額外的工作。

我會同意,兩個單獨的屬性HTTPGET是混亂的,特別是當兩者都包含在項目的WebAPI開箱。當我意外地包含錯誤的名稱空間時,這讓我感到有些不安。

+0

很好的答案。這個鏈接也幫助我:http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api – 2013-05-14 17:15:28

相關問題