Search⌘ K
AI Features

HTTP POST and PUT

Explore how to create and handle HTTP POST and PUT requests in ASP.NET Core APIs. Understand how to add new data asynchronously with POST and update existing data with PUT while managing exceptions and saving changes securely in the database.

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

C#
[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 be User but that would not be able to handle exceptions. A different return type is needed for exceptions. To allow the return type to be either User or an exception, use ActionResult<>.
  • Task<>: This allows a task to be performed asynchronously.

Similar to your controller that returned views, you are adding new data ...