A web API action method is a method on a controller that handles an HTTP request. Unlike an MVC action that usually renders a Razor view, it generally returns data or an HTTP result that a client application can use. A controller can group related actions, such as listing items and retrieving one item. section 20.1 section 19.5.1
To make controller actions available, register controller services with AddControllers() and map their endpoints with MapControllers(). This setup does not add Razor view-rendering services. section 20.1
Listing 20.2 A simple web API controller
[ApiController] #1
public class FruitController : ControllerBase #2
{
List<string> _fruit = new List<string> #3
{ #3
"Pear", #3
"Lemon", #3
"Peach" #3
}; #3
[HttpGet("fruit")] #4
public IEnumerable<string> Index() #5
{ #6
return _fruit; #6
} #6
}
The FruitController example has a public Index action marked [HttpGet("fruit")]. A GET request to /fruit runs the action; its returned list is serialized as JSON. section 20.1
An action can return data directly when a successful response is enough. When it must also handle an error, ActionResult<T> lets it return either data or a result such as NotFound(). Returned data becomes the response body; the successful example produces 200 OK. With [ApiController], an error response such as 404 can use the standard ProblemDetails format. section 20.1 section 20.7
Listing 20.3 A web API action returning IActionResult to handle error conditions
[HttpGet("fruit/{id}")] #1
public ActionResult<string> View(int id) #2
{
if (id >= 0 && id < _fruit.Count) #3
{
return _fruit[id]; #4
}
return NotFound(); #5
}
The View action accepts an id, returns the matching fruit when the id is valid, and returns NotFound() otherwise. Its ActionResult<string> signature accommodates both outcomes. section 20.1
Routing attributes connect an action to a URL. Attributes such as [HttpGet] and [HttpPost] also select by HTTP verb; a route template can contain parameters, and one action can have multiple templates. With attribute routing, the controller and method names do not determine the URL unless the template uses their tokens. section 20.3 section 20.7
After routing selects the action, model binding supplies values from the request and validation records errors in ModelState. Keep the action focused on handling the request: call application services for business behavior, then return an API model or HTTP result. This lets the same business logic serve different kinds of interface. section 20.2
The [ApiController] attribute reduces common API boilerplate. Its conventions include binding suitable parameters from the request body, generating 400 Bad Request for invalid requests, and using ProblemDetails for status-code errors. section 20.7


