`[HttpPost]` marks an ASP.NET Core controller action as available only for HTTP POST requests. It selects an action by request method; it does not, by itself, read submitted values or validate them. section 19.4.2 section 9.3.5
One form URL, two actions
A controller can use `[HttpGet]` on `RsvpForm()` to display a form and `[HttpPost]` on `RsvpForm(GuestResponse guestResponse)` to receive its submission. Both actions use the same URL; ASP.NET Core chooses between them using the request method. Model binding populates `guestResponse` from form fields. The POST action can then store the response and return a thank-you view. section 3.2.6
Listing 3.11 Adding a method in the HomeController.cs file in the Controllers folder
using Microsoft.AspNetCore.Mvc;
using PartyInvites.Models;
namespace PartyInvites.Controllers {
public class HomeController : Controller {
public IActionResult Index() {
return View();
}
[HttpGet]
public ViewResult RsvpForm() {
return View();
}
[HttpPost]
public ViewResult RsvpForm(GuestResponse guestResponse) {
// TODO: store response from guest
return View();
}
}
}
See the controller listing for the paired `[HttpGet]` and `[HttpPost]` actions. The POST action initially has a placeholder for storing the bound response. section 3.2.6
The attribute also appears in larger submission workflows:
- At checkout, a POST action receives a model-bound `Order`. It checks `ModelState.IsValid` and adds an error if the cart is empty before deciding whether to process the order. section 9.3.5
- In a create form, the GET action supplies an editor view model; the POST action receives submitted data, validates it, and prepares a new object for database storage. If validation fails, it rebuilds the view model for the editor. section 31.2.3
- For a JSON API, `[HttpPost]` selects the POST action while `[FromBody]` on its `Product` parameter tells model binding to parse the request body. The two attributes have different jobs. section 19.4.2
Listing 19.10 Sending a POST request to the example application
Invoke-RestMethod http://localhost:5000/api/products -Method POST -Body (@
{ Name="Soccer Boots"; Price=89.99; CategoryId=2; SupplierId=2} |
ConvertTo-Json) -ContentType "application/json"
This PowerShell request posts JSON to `/api/products`. Requesting that URL afterward shows the stored object. section 19.4.2
