HTTP POST and PUT
Learn to create action methods for creating and updating data via JSON Web APIs.
We'll cover the following...
POST
You will create an action method to handle POST requests and call it PostUser()
. It will take the object User
as an input parameter.
Code snippet
Press + to interact
[HttpPost]public async Task<ActionResult<User>> PostUser(User user){_context.Users.Add(user);await _context.SaveChangesAsync();return CreatedAtAction("GetUser", new { id = user.ID }, user);}
Explanation
The method is annotated with [HttpPost]
. This will help the framework identify the request type. The route will be /Api/User
with request type POST.
Your action method return type is Task<ActionResult<User>>
. Break this down to get a better understanding of what is going on:
ActionResult<>
: The return type could beUser
but that would not be able to handle exceptions. A different return type is needed for exceptions. To