The Analogy: The Full-Service Desk
Next to the express counter there is a desk with a clerk, a queue, a rack of forms and a folder of house procedures. Before anything reaches the clerk, a form has been filled in and checked: fields present, numbers in range, signature where it belongs. If the form is wrong it comes back over the counter with the offending lines circled, and the clerk never sees it. If it is right, the clerk does one job with the certainty that the paperwork is valid.
A controller is that desk. [ApiController] is the folder of house procedures: complex parameters are read from the body without being asked, invalid models are rejected with a field-by-field 400 before the action runs, and client errors come back as problem documents rather than empty responses. The action method is the clerk — it receives already-validated, already-typed input and does one thing.
The cost is indirection. Behaviour that a minimal API attaches explicitly to an endpoint is here supplied by attributes, conventions and filters that live somewhere else in the project. The benefit is that a large API written this way has one shape: fifty actions across ten controllers all bind, validate and report errors identically, and a new team member learns the pattern once.
Choosing between the two desks is not about performance for most services; it is about whether the shared paperwork earns its keep. A handful of endpoints, or endpoints that each need something different, suit the express counter. Dozens of endpoints that all need the same validation, the same error shape and the same filters suit the full desk.
Syntax or Core Structure
A controller is a public class deriving from ControllerBase, discovered at startup and routed by its attributes. This program registers one, drives it, and prints what a client sees:
using System.ComponentModel.DataAnnotations;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.AddControllers(); // discovers public ControllerBase types
builder.Services.AddSingleton<ProductStore>();
WebApplication app = builder.Build();
app.Urls.Add("http://127.0.0.1:5215");
app.MapControllers(); // attribute routes become endpoints
await app.StartAsync();
using HttpClient client = new HttpClient { BaseAddress = new Uri("http://127.0.0.1:5215") };
await Call(HttpMethod.Get, "/api/products");
await Call(HttpMethod.Get, "/api/products/2");
await Call(HttpMethod.Get, "/api/products/99");
await Call(HttpMethod.Post, "/api/products", new { name = "Washer", priceCents = 125 });
await Call(HttpMethod.Post, "/api/products", new { name = "", priceCents = 0 });
await Call(HttpMethod.Delete, "/api/products/1");
await app.StopAsync();
async Task Call(HttpMethod method, string path, object? body = null)
{
HttpRequestMessage request = new HttpRequestMessage(method, path);
if (body is not null)
{
request.Content = JsonContent.Create(body, body.GetType());
}
HttpResponseMessage response = await client.SendAsync(request);
string text = await response.Content.ReadAsStringAsync();
Console.WriteLine((int)response.StatusCode + " " + method + " " + path +
" loc " + (response.Headers.Location?.PathAndQuery ?? "-"));
Console.WriteLine(" " + Summarise(text));
}
// A problem document carries a traceId and a type URI that change between
// requests and releases, so only the stable parts are printed.
static string Summarise(string json)
{
if (json.Length == 0)
{
return "(no body)";
}
using JsonDocument document = JsonDocument.Parse(json);
JsonElement root = document.RootElement;
if (root.ValueKind != JsonValueKind.Object)
{
return json;
}
if (root.TryGetProperty("errors", out JsonElement errors))
{
return "problem: " + errors.EnumerateObject().Count() + " field error(s)";
}
return root.TryGetProperty("title", out JsonElement title)
? "problem: " + title.GetString() + " " + root.GetProperty("status").GetInt32()
: json;
}
public record Product(int Id, string Name, int PriceCents);
// DataAnnotations on a request record: [ApiController] turns failures into a 400.
public record CreateProduct(
[property: Required, MinLength(2)] string Name,
[property: Range(1, 1_000_000)] int PriceCents);
[ApiController]
[Route("api/products")]
public sealed class ProductsController : ControllerBase
{
private readonly ProductStore store;
public ProductsController(ProductStore store) => this.store = store; // injected per request
[HttpGet]
public ActionResult<Product[]> List() => Ok(store.All());
[HttpGet("{id:int}")]
public ActionResult<Product> Get(int id) =>
store.Find(id) is Product found ? Ok(found) : NotFound();
[HttpPost]
public ActionResult<Product> Create([FromBody] CreateProduct body) // [FromBody] is inferred
{
Product created = store.Add(body.Name, body.PriceCents);
return CreatedAtAction(nameof(Get), new { id = created.Id }, created);
}
[HttpDelete("{id:int}")]
public IActionResult Delete(int id) => store.Remove(id) ? NoContent() : NotFound();
}
public sealed class ProductStore
{
private readonly List<Product> items = new List<Product>
{
new Product(1, "Bolt", 250),
new Product(2, "Nut", 90)
};
public Product[] All() => items.ToArray();
public Product? Find(int id) => items.FirstOrDefault(p => p.Id == id);
public Product Add(string name, int priceCents)
{
Product created = new Product(items.Count + 1, name, priceCents);
items.Add(created);
return created;
}
public bool Remove(int id) => items.RemoveAll(p => p.Id == id) > 0;
}
Output:
200 GET /api/products loc -
[{"id":1,"name":"Bolt","priceCents":250},{"id":2,"name":"Nut","priceCents":90}]
200 GET /api/products/2 loc -
{"id":2,"name":"Nut","priceCents":90}
404 GET /api/products/99 loc -
problem: Not Found 404
201 POST /api/products loc /api/products/3
{"id":3,"name":"Washer","priceCents":125}
400 POST /api/products loc -
problem: 2 field error(s)
204 DELETE /api/products/1 loc -
(no body)
There is no validation code in that controller, yet the invalid POST came back as 400 with two field errors. [ApiController] installs a filter that inspects ModelState before the action runs and short-circuits with a ValidationProblemDetails if anything failed, so the action body only ever sees input that satisfied its annotations.
The 404 is a problem document rather than an empty response for the same reason: [ApiController] maps client-error results to ProblemDetails, filling in title, status, a type URI and a traceId. Only the stable fields are printed here, because the trace id changes on every request and the type URI has changed between .NET releases.
CreatedAtAction deserves the attention. It did not build "/api/products/" + id by hand; it asked the routing table for the URL of the Get action with id = 3. Rename the route template and the Location header follows, which is the difference between a header that is right by construction and one that is right until someone edits a string.
Technical Depth: Conventions, Binding and Filters
What [ApiController] actually turns on
| Behaviour | Effect | How to switch it off |
|---|---|---|
| Attribute routing required | Conventional {controller}/{action} routes no longer apply | Not configurable; use attributes |
| Inferred binding sources | Complex types come from the body, simple ones from route or query, registered services from DI | Annotate explicitly |
Automatic 400 on invalid ModelState | The action never runs | options.SuppressModelStateInvalidFilter = true |
| Problem details for client errors | NotFound() and friends return a document, not an empty body | options.SuppressMapClientErrors = true |
[FromForm] implies multipart | Form parameters bind from multipart bodies | Annotate explicitly |
Suppressing the model-state filter is occasionally the right call — when an endpoint needs to return its own error shape — and it means the action must check ModelState.IsValid itself and call ValidationProblem().
Naming the binding source
Inference covers most cases; the attributes exist for the rest.
| Attribute | Reads from | Typical use |
|---|---|---|
[FromRoute] | Route values | {id} when the parameter name differs from the token |
[FromQuery] | Query string | Filters, paging, and complex query objects |
[FromBody] | Request body, deserialised | The one payload per request |
[FromForm] | Multipart or urlencoded form | File uploads and browser form posts |
[FromHeader] | A request header | If-Match, X-Correlation-Id, API versions |
[FromServices] | The container | A service needed by one action only |
Two rules cause most of the confusion. Only one parameter can bind from the body, and a complex type that should have come from the query string binds from the body unless it is marked [FromQuery]. In [Route("api/[controller]")] the [controller] token is replaced with the class name minus the Controller suffix, so ProductsController serves api/Products — matching is case-insensitive, but generated links keep the casing of the template.
Return types
| Signature | Says | Best for |
|---|---|---|
Product | Always 200 with this shape | Simple reads that cannot fail |
IActionResult | Any status, unknown shape | Actions with no single success type, such as a delete |
ActionResult<Product> | 200 with Product, or another status | Almost everything else |
Task<ActionResult<Product>> | The same, asynchronously | Anything touching I/O |
ActionResult<T> is the useful one because it documents the success type for OpenAPI while still allowing NotFound(). Add [ProducesResponseType(StatusCodes.Status404NotFound)] for the failures the generated document cannot infer.
The filter pipeline
Filters are the controller equivalent of endpoint filters, with more stages:
| Stage | Interface | Runs |
|---|---|---|
| Authorization | IAuthorizationFilter | First; short-circuits with 401 or 403 |
| Resource | IResourceFilter | Around everything below, including binding — where caching belongs |
| Action | IActionFilter | Around the action, after binding, so it sees the arguments |
| Exception | IExceptionFilter | Only when the action throws |
| Result | IResultFilter | Around writing the response |
Each stage runs in order of the Order property, then by scope: global filters, then controller-level, then action-level. Prefer IAsyncActionFilter over the synchronous pair — one method, one await next(), and no chance of forgetting the "executed" half.
Controllers or minimal APIs?
| Reach for controllers when | Reach for minimal APIs when |
|---|---|
| Many endpoints need identical validation and error shapes | Endpoints are few, or each is different |
You want [Authorize], filters and conventions in one place | You want every behaviour visible at the endpoint |
| The team already knows MVC and the project is large | Startup time and allocation matter, or the service is small |
| You need model binding for forms and file uploads | The payloads are JSON and simple |
The two coexist in one application. app.MapControllers() and app.MapGet(...) register into the same endpoint table, so a controller-based API can grow a couple of minimal endpoints for health checks without a rewrite.
Real World Example: A CSV Import Endpoint
Almost every business system has to accept a file from somewhere else, and file endpoints fail differently from JSON ones: the payload is large, the format is somebody else's, and half the rows are usually fine. This controller accepts a multipart upload, validates the envelope with annotations, validates each row itself, and reports both halves.
using System.ComponentModel.DataAnnotations;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.AddControllers();
builder.Services.AddSingleton<CatalogStore>();
WebApplication app = builder.Build();
app.Urls.Add("http://127.0.0.1:5216");
app.MapControllers();
await app.StartAsync();
using HttpClient client = new HttpClient { BaseAddress = new Uri("http://127.0.0.1:5216") };
string csv = """
name,priceCents
Bolt,250
X,90
Nut,abc
Washer,125
""";
await Upload("warehouse-sync", csv); // two good rows, two rejected by the row check
await Upload("ab", csv); // envelope invalid: the action never runs
await Upload("warehouse-sync", null); // no file part at all
await Show("/api/catalog");
await app.StopAsync();
async Task Upload(string source, string? content)
{
using MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(new StringContent(source), "source");
if (content is not null)
{
form.Add(new StringContent(content, Encoding.UTF8, "text/csv"), "file", "products.csv");
}
HttpResponseMessage response = await client.PostAsync("/api/catalog/import", form);
Console.WriteLine((int)response.StatusCode + " POST /api/catalog/import source " + source +
(content is null ? " (no file)" : string.Empty));
Console.WriteLine(" " + Summarise(await response.Content.ReadAsStringAsync()));
}
async Task Show(string path)
{
HttpResponseMessage response = await client.GetAsync(path);
Console.WriteLine((int)response.StatusCode + " GET " + path);
Console.WriteLine(" " + Summarise(await response.Content.ReadAsStringAsync()));
}
static string Summarise(string json)
{
if (json.Length == 0)
{
return "(no body)";
}
using JsonDocument document = JsonDocument.Parse(json);
JsonElement root = document.RootElement;
if (root.ValueKind == JsonValueKind.Object && root.TryGetProperty("errors", out JsonElement e))
{
return "problem: " + e.EnumerateObject().Count() + " field error(s)";
}
return json;
}
public record Product(int Id, string Name, int PriceCents);
public record ImportReport(string Source, int Imported, string[] Rejected);
// The envelope: annotations describe it, so [ApiController] rejects a bad one for us.
public sealed class ImportRequest
{
[Required]
public IFormFile? File { get; set; }
[Required, MinLength(3)]
public string? Source { get; set; }
}
[ApiController]
[Route("api/catalog")]
public sealed class CatalogController : ControllerBase
{
private const long MaxBytes = 512 * 1024;
private readonly CatalogStore store;
public CatalogController(CatalogStore store) => this.store = store;
[HttpGet]
public ActionResult<Product[]> List() => Ok(store.All());
[HttpPost("import")]
[RequestSizeLimit(MaxBytes)]
public async Task<ActionResult<ImportReport>> Import(
[FromForm] ImportRequest request, CancellationToken token)
{
IFormFile file = request.File!; // a missing file was already rejected
if (file.Length > MaxBytes)
{
ModelState.AddModelError("file", "file must be 512 KB or smaller");
return ValidationProblem(ModelState);
}
List<string> rejected = new List<string>();
int imported = 0;
int line = 0;
using StreamReader reader = new StreamReader(file.OpenReadStream(), Encoding.UTF8);
while (await reader.ReadLineAsync(token) is string text)
{
line++;
if (line == 1 && text.StartsWith("name,", StringComparison.OrdinalIgnoreCase))
{
continue; // header row
}
string[] parts = text.Split(',');
if (parts.Length != 2 || parts[0].Trim().Length < 2 ||
!int.TryParse(parts[1], out int cents) || cents < 1)
{
rejected.Add("line " + line + ": " + (text.Length == 0 ? "(blank)" : text));
continue; // one bad row must not fail the whole file
}
store.Add(parts[0].Trim(), cents);
imported++;
}
return Ok(new ImportReport(request.Source!, imported, rejected.ToArray()));
}
}
public sealed class CatalogStore
{
private readonly List<Product> items = new List<Product>();
private int nextId;
public Product[] All() => items.ToArray();
public Product Add(string name, int priceCents)
{
Product created = new Product(++nextId, name, priceCents);
items.Add(created);
return created;
}
}
Output:
200 POST /api/catalog/import source warehouse-sync
{"source":"warehouse-sync","imported":2,"rejected":["line 3: X,90","line 4: Nut,abc"]}
400 POST /api/catalog/import source ab
problem: 1 field error(s)
400 POST /api/catalog/import source warehouse-sync (no file)
problem: 1 field error(s)
200 GET /api/catalog
[{"id":1,"name":"Bolt","priceCents":250},{"id":2,"name":"Washer","priceCents":125}]
The endpoint validates at two levels, and the difference is visible in the output. The envelope — is there a file, is the source named — is described by annotations, so a bad envelope is rejected before the action runs and nothing is imported. The rows are somebody else's data, so a bad row cannot be allowed to fail the request: two rows imported and two reported back is the correct answer for a file, and the caller gets enough detail to fix the source.
The file is read as a stream rather than a string. ASP.NET Core buffers a multipart upload in memory when it is small and spools it to a temporary file when it is not, so OpenReadStream works the same either way and a 400 MB file does not become a 400 MB string. [RequestSizeLimit] rejects an oversized body before the action is reached, the explicit length check covers the case where the limit is configured elsewhere, and the CancellationToken stops the loop when the client disconnects instead of importing rows nobody is waiting for.
File endpoints need a paragraph of suspicion. file.FileName is a string chosen by the caller: it can contain .., a drive letter or a name that collides with something important, so it must never be used to build a path — generate your own name and keep the original only as metadata. The declared content type is equally untrustworthy, so validate by parsing rather than by extension. And this endpoint has no authentication at all: an open import endpoint lets anyone write to the catalogue, which is a data-integrity hole rather than a mere information leak. The security module adds [Authorize] and the policies behind it.
When the action does report an envelope problem of its own — the size check — it calls ValidationProblem(ModelState), producing exactly the shape the automatic filter produces. That consistency is the real dividend of the full desk: a client writes one error handler and it works for every endpoint in the API. One caveat if a browser form ever posts here: form endpoints reached from a page need antiforgery protection, which [ValidateAntiForgeryToken] supplies and which a token-authenticated API does not require.
Common Mistakes
- Business logic in the controller. An action that queries, calculates, writes and formats cannot be tested without HTTP and cannot be reused by a worker. Keep the action to binding, one call into a service, and mapping the outcome to a status code.
- Returning domain entities directly. Serialising an EF entity exposes internal columns, drags in whatever navigation properties happen to be loaded, and makes a column rename a breaking API change. Return a response record.
- Building URLs by string concatenation.
"/api/products/" + idsurvives until someone changes the route template.CreatedAtActionandLinkGeneratorask the routing table, so they change with it. - Trusting the uploaded file name or content type. Both are supplied by the caller. Never use
FileNamein a path, never decide how to parse from the extension, and always cap the size before reading.
- Forgetting that a controller is created per request. Fields on a controller are fine, static fields are shared by every request in the process. Constructor-inject what the action needs and keep no state between requests.
- Reading a whole upload into memory.
await file.CopyToAsync(memoryStream)on a large file turns one request into hundreds of megabytes of allocation. Stream it, and set a size limit that a hostile caller cannot exceed. - Two actions the router cannot tell apart.
[HttpGet("{id}")]and[HttpGet("{name}")]on the same controller produce an ambiguous-match exception at request time, not at startup. Constrain the templates —{id:int}and{name:alpha}— or give one a distinct segment. - Sprinkling
[Authorize]per action and missing one. The default should be secure: apply the attribute to the controller or a global convention and mark the deliberate exceptions with[AllowAnonymous], so a new action is protected by omission rather than exposed by it.
Best Practices
- Keep controllers thin and per-resource. If a class has fifteen actions it is probably two resources wearing one name.
- Put
[ApiController]on every API controller and let it own the error shape, rather than hand-writingif (!ModelState.IsValid)in each action. - Describe requests with annotated request records so the rules live with the data and the generated OpenAPI document reflects them.
- Annotate the failure cases with
[ProducesResponseType]; the success type is inferred fromActionResult<T>but the 404s and 409s are not. - Use
IAsyncActionFilterfor cross-cutting behaviour that needs the bound arguments, and middleware for anything that must also apply to unmatched requests. - Take
CancellationTokenin every asynchronous action and pass it all the way down to the database call. - Generate URLs from the routing table, never from string concatenation, so route changes cannot silently break
Locationheaders or links. - For uploads, set an explicit size limit, stream to its destination, generate your own file name, and validate the content by parsing it.
Practice Exercises
- Add an update action. Give
ProductsControlleraPUT /api/products/{id:int}that replaces a product, returning204on success and404for a missing id, and prove both paths through the in-process client. - Write an action filter. Add an
IAsyncActionFilterthat rejects any request whoseX-Api-Keyheader does not match a configured value, and show that the action is never entered for a rejected request by printing from both the filter and the action. - Report row errors properly. Change the import so the response uses a
ValidationProblemwhen every row fails, and200with a report when some succeed. Explain in a comment which status code a caller's retry logic can act on. - Convert one endpoint both ways. Rewrite
GET /api/products/{id:int}as a minimal API endpoint returningResults<Ok<Product>, NotFound>, keep the controller version alive on a different route, and list the concrete differences in what each one needs you to write.