0

I've been following along with a tutorial here to get my head around authentication in Web API with OAuth.

I have worked on Web API before, where I named the methods to start with Get, Put, Post etc. in order that they were routed to depending on the http verb. I also know that actions can be decorated with attributes ([HttpGet] etc) to denote the verb that maps to them.

In the tutorial, there is an action on a controller that looks like this:

// 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();
}

This method, as the comment suggests, responds to POST requests. I cannot see how the Web API knows that this action is for POST. Can anyone enlighten me?

Fordio
  • 3,410
  • 2
  • 14
  • 18

1 Answers1

4

If you look at the documentation for Web API Routing and Action Selection:

...

HTTP Methods. The framework only chooses actions that match the HTTP method of the request, determined as follows:

  1. You can specify the HTTP method with an attribute: AcceptVerbs, HttpDelete, HttpGet, HttpHead, HttpOptions, HttpPatch, HttpPost, or HttpPut.
  2. Otherwise, if the name of the controller method starts with "Get", "Post", "Put", "Delete", "Head", "Options", or "Patch", then by convention the action supports that HTTP method.
  3. If none of the above, the method supports POST.

...

and the source for ReflectedHttpActionDescriptor.cs (line number 294-300):

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

return supportedHttpMethods;
...

You'll find your answer:

POST is the default HTTP Verb for action method in Web API.


Also, if you search a bit more on SO, You'll find the following question:
Is there a default verb applied to a Web API ApiController method?

Although it's a different question, but the problem is basically the same as yours.

Community
  • 1
  • 1
IronGeek
  • 4,764
  • 25
  • 27