CodeOath
← All posts
.NET Core / Web API70 min total · 19 parts

Building REST APIs with ASP.NET Core: Routing, Middleware, and Dependency Injection

Contents — Part 5 of 19: Controllers, [ApiController], and ControllerBase
Part 5 of 19 · ~1 min

Controllers, [ApiController], and ControllerBase

ControllerBase (not Controller, which additionally supports views for MVC/Razor — irrelevant for a pure API) provides the helper methods used throughout this reference: Ok(), NotFound(), CreatedAtAction(), BadRequest(), and access to HttpContext, User, and ModelState.

[ApiController] turns on several conventions at once, which is exactly why bare API controllers look shorter than you'd expect:

  • Automatic model validation — if the request body doesn't satisfy data-annotation rules on CreateOrderRequest (e.g. [Required]), a 400 response is returned automatically, before your action method's body even runs.
  • Inferred binding sourcesid in the route is bound from the URL, request in a POST is inferred as coming from the request body, without needing [FromRoute]/[FromBody] spelled out every time (the inference rules are covered in the next section).
  • Attribute routing is required — no legacy convention-based routing fallback, keeping every route explicit and grep-able.
  • Automatic ProblemDetails responses for client errors — a validation failure comes back as a structured application/problem+json body by default, not a bare 400 with no explanation.