ASP.NET Core MVC Interview Question #28
What is the purpose of the [HttpPost] attribute?
Controllers, Actions, Model Binding & Action Results Junior Beginner
Quick Interview Answer
HttpPost restricts an action to HTTP POST requests. POST actions commonly process form submissions that create or change server-side state.
Detailed Explanation
HttpPost restricts an action to HTTP POST requests. POST actions commonly process form submissions that create or change server-side state.
For browser forms, POST actions should normally validate input, verify anti-forgery protection where appropriate, perform the operation through application services, and redirect after successful processing.
Code Example
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(ProductEditViewModel model)
{
if (!ModelState.IsValid)
return View(model);
await _service.CreateAsync(model);
return RedirectToAction(nameof(Index));
}