`[HttpGet]` marks an ASP.NET Core MVC controller action as handling HTTP GET requests. Place it above the C# method. It selects which requests can invoke the action; it does not, by itself, define everything the action returns. section 19.4.2
One URL, two jobs
A `HomeController` can have two `RsvpForm` actions at the same URL. `[HttpGet]` marks the action that returns the RSVP form view; `[HttpPost]` marks the overload that receives a submitted `GuestResponse`. MVC chooses between them using the request method. The POST parameter is populated through model binding, not by `HttpGet`. section 3.2.6
In a web-service controller, routing adds another part to the choice. With `[Route("api/[controller]")]` on `ProductsController`, `[HttpGet]` handles `GET /api/products`; `[HttpGet("{id}")]` handles `GET /api/products/{id}`. For these actions, the HTTP-method attributes and route patterns matter more than the C# action names. section 19.4.2
Listing 19.6 The contents of the ProductsController.cs file in the Controllers folder
using Microsoft.AspNetCore.Mvc;
using WebApp.Models;
namespace WebApp.Controllers {
[Route("api/[controller]")]
public class ProductsController : ControllerBase {
[HttpGet]
public IEnumerable<Product> GetProducts() {
return new Product[] {
new Product() { Name = "Product #1" },
new Product() { Name = "Product #2" },
};
}
[HttpGet("{id}")]
public Product GetProduct() {
return new Product() {
ProductId = 1, Name = "Test Product"
};
}
}
}
The controller listing shows both forms of `[HttpGet]` beside the controller-level route, making the collection and item URL patterns easy to compare. section 19.4.2
Keep each HTTP-method-and-URL-pattern combination mapped to one action; if multiple actions match, MVC cannot choose and throws an exception. As a rule of thumb, use GET for read-only retrieval and POST for operations that change application state. section 19.4.2
