MVC Controllers
Minimal APIs put each endpoint in a lambda inside Program.cs. Controllers are the older, class-based alternative: related endpoints live together as methods (called actions) on a class. Both styles run on the same routing and middleware, and you can mix them in one app. Controllers are still the most common style in existing ASP.NET Core codebases and are the "C" of the Model–View–Controller pattern.
| Piece | Role |
|---|---|
| Model | The data and business rules (Product, Order, a service that loads them) |
| View | Renders HTML for the user (Razor .cshtml files) |
| Controller | Receives the request, talks to the model, chooses what to return |
For a JSON API you only need the M and the C — the "view" is the serialized object.
Registering controllers
Two lines in Program.cs turn controllers on:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers(); // API controllers only
// builder.Services.AddControllersWithViews(); // controllers + Razor views (MVC web app)
var app = builder.Build();
app.MapControllers(); // map attribute-routed controllers
app.Run();AddControllers registers the services that discover controller classes, bind parameters and format results. MapControllers adds an endpoint for every action that has a route attribute.
An API controller
using Microsoft.AspNetCore.Mvc;
namespace Shop.Controllers;
[ApiController]
[Route("api/[controller]")] // [controller] = class name minus "Controller" → "api/products"
public class ProductsController : ControllerBase
{
private static readonly List<Product> Products =
[
new(1, "Keyboard", 49.90m),
new(2, "Mouse", 19.50m),
];
[HttpGet] // GET api/products
public IEnumerable<Product> GetAll() => Products;
[HttpGet("{id:int}")] // GET api/products/2
public ActionResult<Product> GetById(int id)
{
var product = Products.FirstOrDefault(p => p.Id == id);
return product is null ? NotFound() : product;
}
[HttpPost] // POST api/products
public ActionResult<Product> Create(Product input)
{
var created = input with { Id = Products.Max(p => p.Id) + 1 };
Products.Add(created);
return CreatedAtAction(nameof(GetById), new { id = created.Id }, created);
}
[HttpDelete("{id:int}")]
public IActionResult Delete(int id)
{
var removed = Products.RemoveAll(p => p.Id == id);
return removed == 0 ? NotFound() : NoContent();
}
}
public record Product(int Id, string Name, decimal Price);Key points:
- The class derives from
ControllerBase(no view support) — useControllerinstead when you also return Razor views. [ApiController]enables API conveniences: automatic400responses for invalid models, binding complex parameters from the JSON body, and ProblemDetails for error status codes.[Route]on the class plus[HttpGet]/[HttpPost]/… on actions combine into the final URL template.ActionResult<T>lets an action return either aT(serialized as200 OK) or any result such asNotFound().
$ curl -s localhost:5000/api/products
$ curl -s -i localhost:5000/api/products/7
$ curl -s -X POST localhost:5000/api/products -H "Content-Type: application/json" -d '{"name":"Monitor","price":189}'[{"id":1,"name":"Keyboard","price":49.90},{"id":2,"name":"Mouse","price":19.50}]
HTTP/1.1 404 Not Found
Content-Type: application/problem+json; charset=utf-8
Date: Thu, 16 Oct 2026 09:00:00 GMT
Server: Kestrel
Transfer-Encoding: chunked
{"type":"https://tools.ietf.org/html/rfc9110#section-15.5.5","title":"Not Found","status":404,"traceId":"00-5b1f0c7e9a3d4e21b6c8f0a1d2e3f405-9c1d2e3f4a5b6c7d-00"}
{"id":3,"name":"Monitor","price":189}
Helper methods on ControllerBase
| Method | Status | Typical use |
|---|---|---|
Ok(value) |
200 | Return data explicitly |
CreatedAtAction(action, routeValues, value) |
201 | After a POST; sets the Location header |
NoContent() |
204 | Successful update/delete with no body |
BadRequest(error) |
400 | Input is wrong |
Unauthorized() / Forbid() |
401 / 403 | Authentication / permission problems |
NotFound() |
404 | The resource doesn't exist |
Conflict() |
409 | Duplicate or state conflict |
StatusCode(code, value) |
any | Everything else |
How the framework finds an action
When a request arrives, routing compares the path and HTTP verb against every action's template and invokes the matching method on a fresh controller instance (controllers are created per request, and their constructor parameters come from dependency injection). We can imitate that dispatch with plain reflection and attributes:
using System;
using System.Linq;
using System.Reflection;
var routes = typeof(ProductsController).GetMethods()
.Select(m => (Method: m, Attr: m.GetCustomAttribute<HttpAttribute>()))
.Where(x => x.Attr != null)
.ToList();
foreach (var (verb, path) in new[] { ("GET", "products"), ("POST", "products"), ("GET", "orders") })
{
var match = routes.FirstOrDefault(r => r.Attr.Verb == verb && r.Attr.Path == path);
if (match.Method == null) { Console.WriteLine(quot;{verb} /{path} -> 404"); continue; }
var controller = Activator.CreateInstance(typeof(ProductsController)); // new instance per request
var result = match.Method.Invoke(controller, null);
Console.WriteLine(quot;{verb} /{path} -> {match.Method.Name}() = {result}");
}
[AttributeUsage(AttributeTargets.Method)]
class HttpAttribute : Attribute
{
public string Verb { get; }
public string Path { get; }
public HttpAttribute(string verb, string path) { Verb = verb; Path = path; }
}
class ProductsController
{
[Http("GET", "products")]
public string List() => "[Keyboard, Mouse]";
[Http("POST", "products")]
public string Create() => "201 Created";
}GET /products -> List() = [Keyboard, Mouse]
POST /products -> Create() = 201 Created
GET /orders -> 404
The real framework does this once at startup, builds a fast route table, and caches compiled invokers — but the idea is the same: attributes describe routes, and a new controller handles each request.
Injecting services into a controller
Controllers receive dependencies through their constructor. In .NET 9 a primary constructor keeps it short:
[ApiController]
[Route("api/orders")]
public class OrdersController(IOrderService orders, ILogger<OrdersController> logger) : ControllerBase
{
[HttpGet("{id:int}")]
public async Task<ActionResult<OrderDto>> Get(int id, CancellationToken ct)
{
logger.LogInformation("Loading order {OrderId}", id);
var order = await orders.FindAsync(id, ct);
return order is null ? NotFound() : Ok(order);
}
}Actions can be async and accept a CancellationToken, which is cancelled when the client disconnects.
Tip: Controllers or minimal APIs? For new small services minimal APIs are lighter. Controllers shine when you have many endpoints that share filters, conventions and attributes, or when you are building a server-rendered MVC site with views.
Conventional routing for MVC sites
Web apps with views often use a conventional route instead of attributes:
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");With this pattern, /Products/Details/5 calls ProductsController.Details(5) and / calls HomeController.Index(). Classes ending in Controller are discovered automatically.
Test yourself
Which base class should an API-only controller derive from?
- Controller
- ControllerBase
- PageModel
- ApiController
With [Route("api/[controller]")] on InvoicesController, what is the base URL?
- /InvoicesController
- /api/controller
- /invoices
- /api/Invoices
How often is a controller instance created?
- Once per request
- Once when the app starts
- Once per user session
- Once per thread