2014-10-03 55 views
0

我一直在關注一個教程here,以瞭解如何使用OAuth在Web API中進行身份驗證。爲什麼POST請求映射到此Web API操作方法?

我以前在Web API上工作過,在那裏我命名方法以Get,Put,Post等開頭,以便根據http動詞路由它們。我也知道可以使用屬性([HttpGet]等)來修飾動作以表示映射到它們的動詞。

在本教程中,有一個控制器,它看起來像這樣的一個動作:

// POST api/Account/Register 
[AllowAnonymous] 
[Route("Register")] 
public async Task<IHttpActionResult> Register(UserModel userModel) 
{ 
    if (!ModelState.IsValid) 
     return BadRequest(ModelState); 

    IdentityResult result = await _repo.RegisterUser(userModel); 

    IHttpActionResult errorResult = GetErrorResult(result); 

    if(errorResult != null) 
     return errorResult; 

    return Ok(); 
} 

這種方法,作爲意見建議,響應POST請求。我看不到Web API如何知道此操作是針對POST的。任何人都可以啓發我嗎?

回答

4

如果你看一下文件的Web API Routing and Action Selection

...

HTTP方法。該框架僅選擇如下確定匹配請求的HTTP方法的動作,:

  1. 可以與屬性指定HTTP方法:AcceptVerbsHttpDeleteHTTPGETHttpHeadHttpOptionsHttpPatchHttpPost,或HttpPut
  2. 否則,如果控制器方法的名稱以「Get」,「Post」,「Put」,「Delete」,「Head」,「Options」或「Patch」開頭,那麼按照約定, HTTP方法。
  3. 如果以上都不是,則該方法支持POST。

...

ReflectedHttpActionDescriptor.cs源(行號294-300):

... 
if (supportedHttpMethods.Count == 0) 
{ 
    // Use POST as the default HttpMethod 
    supportedHttpMethods.Add(HttpMethod.Post); 
} 

return supportedHttpMethods; 
... 

你會發現你的答案:

POST是操作方法的默認HTTP Verb在Web API中。


另外,如果你搜索了一下更多的話,你會發現以下問題:
Is there a default verb applied to a Web API ApiController method?

雖然這是一個不同的問題,但問題是基本相同你的。

相關問題