Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 52 ยท MVC, Controllers and Razor

Controllers and Actions

Build web APIs with controllers: ControllerBase, [ApiController], attribute routing, action results, ActionResult<T>, dependency injection and conventions.

Minimal APIs map a URL to a lambda. Controllers do the same thing with classes: a class groups related endpoints, and each public method on it, called an action, handles one route. This is the original ASP.NET Core style (part of the MVC framework: Model, View, Controller), and it is still the most common way to build large APIs because it gives you a familiar structure, built-in conventions and a rich filter system.

In this lesson you will write controllers that return data, use attribute routing and action results, return ActionResult<T>, take dependencies through the constructor, and see what [ApiController] does for you. If you have not met the minimal style yet, Minimal API Endpoints is the comparison point; the C# track has an overview of MVC and Razor, and the next lesson covers binding and filters in depth.

The pieces of a controller

A controller is a public class that, by convention, ends in Controller and derives from ControllerBase. (Controller adds view support for HTML pages; an API does not need it.) Its public methods become actions. The framework creates a new controller instance for every request, so instance fields never carry state between requests; use injected services for that.

Setting it up takes two lines:

C#
builder.Services.AddControllers();   // registers MVC controllers (no views)
// ...
app.MapControllers();                // maps every controller action as an endpoint

Under the hood, controllers become ordinary endpoints in the same routing system the minimal API uses, so the middleware pipeline works the same way for both.

flowchart LR
    A["Request"] --> B["Routing<br/>picks an action"]
    B --> C["New controller instance<br/>(DI creates it)"]
    C --> D["Action method runs"]
    D --> E["Action result<br/>such as Ok or NotFound"]
    E --> F["Result executes<br/>JSON written"]
    F --> G["Response"]

A controller lives for one request: it is created, runs one action and is discarded.

A first controller

The [ApiController] attribute marks a class as an API controller and switches on a group of conventions (explained below). [Route("api/[controller]")] sets the URL prefix; the token [controller] is replaced by the class name without the Controller suffix, so ProductsController serves /api/products.

C# A products controller

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Three conventions did work for you here. Create(CreateProduct request) takes a complex type with no attribute, and [ApiController] inferred that it comes from the JSON body. The invalid body never reached your method: the framework checked the validation attributes and answered 400 with application/problem+json. And CreatedAtAction produced a 201 with a Location header pointing at GetById.

What [ApiController] changes

Applying the attribute to a controller (or to the whole assembly) turns on these behaviors:

  • Attribute routing is required. Every action needs a [Route] or an [HttpGet]-style attribute; there is no conventional URL template.
  • Automatic HTTP 400. If ModelState is invalid (binding failed or validation attributes were broken), the action is not run and a ValidationProblemDetails response is sent.
  • Binding source inference. Complex types are read from the body, simple types come from the route or the query string, and IFormFile from a form.
  • Problem details for errors. Results with an error status code, such as NotFound() with no body, are turned into a ProblemDetails JSON document.

Attribute routing

Routes come from attributes on the class and on each action. They combine: the class attribute is the prefix, the action attribute is the rest. The route template syntax is the same as in the minimal API, including constraints like {id:int} (Route Templates and Constraints).

Attribute Meaning
[Route("api/[controller]")] Prefix for the controller; tokens [controller] and [action] are replaced
[HttpGet], [HttpPost], [HttpPut], [HttpPatch], [HttpDelete] The HTTP method, with an optional template: [HttpGet("{id:int}")]
[NonAction] A public method that must not become an endpoint
[Route("/health")] or [HttpGet("/health")] A leading / ignores the controller prefix

Prefer the explicit HTTP-verb attributes over a bare [Route] on an action. A method with no verb attribute answers every method.

Action results

An action can return a plain value (it becomes 200 OK with JSON), an IActionResult, or an ActionResult<T>. Use the results that match HTTP semantics, available as helper methods on ControllerBase:

Helper Status Typical use
Ok(value) 200 Return data
CreatedAtAction(...), Created(uri, value) 201 After creating a resource
Accepted() 202 Work queued for later
NoContent() 204 Successful delete or update with nothing to return
BadRequest(...), Conflict(...), UnprocessableEntity(...) 400, 409, 422 Client errors
NotFound() 404 Resource does not exist
Unauthorized(), Forbid() 401, 403 Authentication and authorization
File(...), Content(...), StatusCode(...), Problem(...) various Files, text, any status, problem details

ActionResult<T> is the best default for APIs. It lets you return either a T (implicitly converted to 200) or any action result, and it also tells OpenAPI tooling that the success response contains a T. IActionResult hides the success type, and a plain T return makes it impossible to return 404. Asynchronous actions return Task<ActionResult<T>>.

Dependency injection and per-request state

Controllers get their dependencies in the constructor, like any other service (Dependency Injection in ASP.NET Core). Because a controller instance lives for one request, it is safe to inject scoped services such as a database context. ControllerBase also gives you the current request through properties: Request, Response, HttpContext, User and Url.

C# Injected services and a range of results

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice how a handful of helper methods cover every status code the table lists. Get returns a string or a NotFound() from the same method, which is exactly what ActionResult<T> allows. The controller uses a primary constructor to receive the store; because the store is a singleton, the notes persist between requests, while the controller object itself is rebuilt each time.

Controllers need to be public. The framework finds them by scanning the application's public types, so a controller declared as internal or nested privately is silently ignored and every request to it returns 404. In a real project, put them in a Controllers folder; the single-file examples here simply declare them at the bottom of the file.

Practical advice

  • Keep actions thin. An action should translate HTTP into a call to a service and a result back into HTTP. Business rules belong in services you can test without a web server.
  • Prefer ActionResult<T> so that both the data and the error paths are explicit.
  • One resource per controller, named in the plural (OrdersController), with routes that follow REST conventions.
  • Do not store request state in fields. A new instance per request makes this harmless today, but it fails the moment a controller is registered another way.
  • Use CancellationToken as an action parameter for long operations so work stops when the client disconnects.
  • Add [ApiController] everywhere (or once, at assembly level) so the conventions apply consistently.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How long does a controller instance live?

    A new controller is created for every request and discarded afterwards, which is why shared state must live in injected services or static data.
  2. 2. What does [ApiController] do when the request body fails validation?

    With [ApiController], an invalid ModelState produces an automatic 400 response, so your action only runs with valid input.
  3. 3. Why is ActionResult<Product> usually a better return type than Product?

    A plain Product cannot express 404. ActionResult<T> allows both values and results while keeping the success type visible to tools such as OpenAPI.
  4. 4. A controller class is declared internal. What happens?

    Controller discovery only finds public types. An internal controller is ignored and its routes do not exist.
  5. 5. What does the [controller] token in [Route("api/[controller]")] become for ProductsController?

    The token is replaced with the class name minus the Controller suffix, which gives the route api/Products; routing is case-insensitive, so /api/products matches.

Summary

  • A controller is a public class deriving from ControllerBase whose public methods (actions) are mapped to routes with attributes; it is created anew for every request.
  • Register with AddControllers() and map with MapControllers(); the result is ordinary endpoints in the same pipeline as minimal APIs.
  • [ApiController] adds required attribute routing, automatic 400 on invalid models, binding-source inference and problem-details errors.
  • Use the verb attributes and action result helpers (Ok, CreatedAtAction, NoContent, NotFound, Conflict...) and prefer ActionResult<T>.
  • Inject services through the constructor; keep actions thin and business logic in services.

Next: Model Binding and Filters in MVC