A web API controller handles HTTP requests through action methods and returns data or status codes that a client application can use. It uses the ASP.NET Core MVC framework, but unlike a controller that renders Razor views, it typically produces machine-readable responses such as JSON. A mobile app or browser-based client can call its endpoints without receiving an HTML page. section 19.1 section 20.1
Start with an ASP.NET Core Web API project, or configure an application with AddControllers() and MapControllers(). AddControllers() registers controller services without Razor view rendering; MapControllers() makes controller actions available as endpoints. A controller can group related actions, such as listing items and retrieving one item. section 20.1 section 19.6
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 small controller shows the essential shape: [ApiController] on the class, ControllerBase as its base class, and a [HttpGet("fruit")] action returning a list. section 20.1
Return an item—or a missing-item response
A GET request to /fruit returns the list as JSON. A second action can accept an id from /fruit/{id}: return the matching string when it exists, or NotFound() when it does not. Returning ActionResult<string> accommodates both outcomes. section 20.1
Routing selects a controller action for the request. The framework binds and validates input before the action uses application services or data; it then generates the HTTP response. This follows much the same request flow as Razor Pages, but produces a machine-readable response instead of rendering a Razor view. section 20.2 section 20.0
Two attributes do much of the everyday work:
- Use routing attributes such as [HttpGet] and [HttpPost] to connect an action to a URL and HTTP verb. GET and POST can reach different actions at the same URL; a mismatched verb can produce 405 Method Not Allowed. section 20.3 section 20.3.3
- Use [ApiController] for API conventions, including automatic 400 responses for invalid requests, parameter-source inference, and ProblemDetails support. section 20.0
Choose between web API controllers and minimal APIs according to the application’s needs. Controllers provide built-in content negotiation for clients requesting different response formats, but minimal APIs may suit performance-sensitive work better. ASP.NET Core uses one controller framework for both API responses and HTML; “web API controller” describes how the controller is used, not a separate controller stack. section 20.6 section 19.1







