The Analogy: The Express Counter at the Post Office
A post office has a long counter with clerks who can do anything — passports, currency, parcels to Ecuador — and it has an express counter with one clerk who does exactly one thing: hand over a prepaid parcel. No form, no queue ticket, no manual under the desk. The transaction is described entirely by what the customer hands over and what they get back.
A minimal API endpoint is that express counter. The route, the inputs and the response are declared on a single line, and there is no class, no base type, no attribute and no convention to learn before the first request works. app.MapGet("/orders/{id:int}", (int id, OrderStore store) => ...) is the entire contract: the path shape, where each value comes from, and what comes back.
The trade is deliberate. The long counter — controllers, covered next — brings filters, model binders, conventions and a place to hang shared behaviour. The express counter brings almost nothing, which is why it starts faster, allocates less and reads top to bottom. When one endpoint needs shared behaviour, you attach it explicitly to that endpoint or to a group, rather than inheriting it from a base class.
What makes this practical rather than merely small is that the framework still knows what each endpoint does. Returning TypedResults.Ok(order) tells the routing layer the exact type and status code, which is how OpenAPI documents get generated and how a handler can be unit-tested without HTTP at all. The express counter is small, but it is not undocumented.
Syntax or Core Structure
A complete resource — list, read, create, complete, delete — fits in a screen. This program builds one, drives it with an in-process client, and prints every exchange:
using System.Net.Http.Json;
using Microsoft.AspNetCore.Http.HttpResults; // Ok<T>, NotFound, Results<,>
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.AddSingleton<TaskStore>();
WebApplication app = builder.Build();
app.Urls.Add("http://127.0.0.1:5213");
RouteGroupBuilder tasks = app.MapGroup("/tasks");
// bool? done comes from the query string; TaskStore comes from the container.
tasks.MapGet("", (bool? done, TaskStore store) => TypedResults.Ok(store.All(done)));
// The union return type says: this endpoint answers 200 or 404, nothing else.
tasks.MapGet("/{id:int}", Results<Ok<TodoItem>, NotFound> (int id, TaskStore store) =>
store.Find(id) is TodoItem found ? TypedResults.Ok(found) : TypedResults.NotFound());
// A complex type with no attribute is read from the JSON body.
tasks.MapPost("", (NewTodo body, TaskStore store) =>
{
TodoItem created = store.Add(body.Title);
return TypedResults.Created("/tasks/" + created.Id, created);
});
tasks.MapPut("/{id:int}/done", (int id, TaskStore store) =>
store.Complete(id) ? Results.NoContent() : Results.NotFound());
tasks.MapDelete("/{id:int}", (int id, TaskStore store) =>
store.Remove(id) ? Results.NoContent() : Results.NotFound());
await app.StartAsync();
using HttpClient client = new HttpClient { BaseAddress = new Uri("http://127.0.0.1:5213") };
await Call(HttpMethod.Post, "/tasks", new { title = "Ship the release" });
await Call(HttpMethod.Post, "/tasks", new { title = "Write the changelog" });
await Call(HttpMethod.Put, "/tasks/1/done");
await Call(HttpMethod.Get, "/tasks?done=true");
await Call(HttpMethod.Get, "/tasks/9");
await Call(HttpMethod.Delete, "/tasks/2");
await Call(HttpMethod.Get, "/tasks");
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?.ToString() ?? "-") +
" " + (text.Length == 0 ? "(no body)" : text));
}
record TodoItem(int Id, string Title, bool IsDone);
record NewTodo(string Title);
sealed class TaskStore
{
private readonly List<TodoItem> items = new List<TodoItem>();
private int nextId;
public TodoItem[] All(bool? done) =>
items.Where(i => done is null || i.IsDone == done).ToArray();
public TodoItem? Find(int id) => items.FirstOrDefault(i => i.Id == id);
public TodoItem Add(string title)
{
TodoItem created = new TodoItem(++nextId, title, false);
items.Add(created);
return created;
}
public bool Complete(int id)
{
int index = items.FindIndex(i => i.Id == id);
if (index < 0)
{
return false;
}
items[index] = items[index] with { IsDone = true };
return true;
}
public bool Remove(int id) => items.RemoveAll(i => i.Id == id) > 0;
}
Output:
201 POST /tasks loc /tasks/1 {"id":1,"title":"Ship the release","isDone":false}
201 POST /tasks loc /tasks/2 {"id":2,"title":"Write the changelog","isDone":false}
204 PUT /tasks/1/done loc - (no body)
200 GET /tasks?done=true loc - [{"id":1,"title":"Ship the release","isDone":true}]
404 GET /tasks/9 loc - (no body)
204 DELETE /tasks/2 loc - (no body)
200 GET /tasks loc - [{"id":1,"title":"Ship the release","isDone":true}]
Five endpoints, no controller, no attributes, and every status code in the output is a deliberate choice rather than a default. 201 carries a Location header pointing at the resource that was just created, 204 says "done, nothing to tell you", and the two 404s come from the handler deciding the resource does not exist rather than from routing failing to find a match.
One detail is a bug waiting to happen in anything busier than a demo: TaskStore is a singleton holding a List, so two concurrent requests can corrupt it. The lesson on dependency injection covers why — a singleton is shared by every request — and a real store would be scoped around a database, or would use a concurrent collection.
Technical Depth: Binding, Results and Filters
Where each parameter comes from
There are no attributes in the example because the defaults already cover the common cases, in this order:
| Parameter looks like | Bound from |
|---|---|
A name that matches a route token, such as int id for /{id} | The route |
A simple type with no matching route token, such as bool? done | The query string |
A type registered in the container, such as TaskStore | Dependency injection |
A complex type such as NewTodo | The JSON body — at most one per endpoint |
HttpContext, HttpRequest, ClaimsPrincipal, CancellationToken | Supplied by the framework |
Two extensions matter once endpoints grow. A type with a static TryParse binds from a single string value, so record Coordinates(double Lat, double Lon) with TryParse can arrive as ?at=51.5,-0.12. A type with a static BindAsync(HttpContext) takes over its own binding completely, which is how a paging or filtering object can read several headers and query values at once.
For a handler with six query parameters, [AsParameters] collapses them into one object without changing the wire format:
record ListQuery(int? Page, int? PageSize, string? Sku);
app.MapGet("/orders", ([AsParameters] ListQuery query, OrderStore store) => /* ... */);
Each property still binds from its own source, so ?page=2&sku=BOLT-01 works exactly as it did with loose parameters — but the handler signature stays short and the object can carry its own validation.
Results or TypedResults
Both produce the same bytes on the wire. The difference is what the compiler and the framework can see:
| Concern | Results.Ok(order) | TypedResults.Ok(order) |
|---|---|---|
| Static type | IResult | Ok<Order> |
| Unit testable without HTTP | Only by casting | Yes, assert on .Value and .StatusCode |
| OpenAPI knows the response type | Only if you add .Produces<Order>() | Inferred automatically |
Works in a Results<T1, T2> union | No | Yes |
Prefer TypedResults in new code. When an endpoint has more than one outcome, declare the union as the return type:
static Results<Ok<Order>, NotFound, ProblemHttpResult> Get(int id, OrderStore store) =>
id < 1
? TypedResults.Problem("id must be positive", statusCode: 400)
: store.Find(id) is Order found
? TypedResults.Ok(found)
: TypedResults.NotFound();
The union both documents the endpoint and stops a later edit from quietly returning a fourth shape.
Endpoint filters
A filter wraps one endpoint or one group, and unlike middleware it runs after binding, so it can read and even replace the bound arguments:
app.MapPost("/orders", (CreateOrder body, OrderStore store) => /* ... */)
.AddEndpointFilter(async (context, next) =>
{
CreateOrder body = context.GetArgument<CreateOrder>(0);
if (body.Quantity < 1)
{
return TypedResults.BadRequest("quantity must be positive");
}
return await next(context); // returning without calling next short-circuits
});
Filters compose in registration order, they can inspect the result on the way out, and AddEndpointFilter<T> lets a reusable filter class be attached to a whole MapGroup. That is the minimal-API answer to action filters: explicit at the point of use rather than discovered by convention.
Status codes worth being deliberate about
| Situation | Status | Extra |
|---|---|---|
| Read succeeded | 200 | The representation |
| Created a resource | 201 | Location header pointing at it |
| Accepted for later processing | 202 | Location of a status endpoint |
| Succeeded with nothing to say | 204 | No body at all |
| Client sent something invalid | 400 | ValidationProblem with per-field errors |
| Resource does not exist | 404 | No body, or a problem document |
| Version conflict on write | 409 | What the current state is |
| Unsupported filter or sort value | 400 | Never 500 — the server is fine |
Real World Example: A Paged, Validated Orders Resource
Two things separate a demo endpoint from one that survives a real client: it never returns an unbounded list, and it rejects nonsense with a per-field explanation instead of a stack trace. This example does both with one reusable filter and one query object, and drives it through six requests including the failing ones.
using System.Net.Http.Json;
using System.Text.Json;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.AddSingleton<OrderStore>();
WebApplication app = builder.Build();
app.Urls.Add("http://127.0.0.1:5214");
RouteGroupBuilder orders = app.MapGroup("/api/orders").WithTags("Orders");
orders.MapGet("", ([AsParameters] ListQuery query, OrderStore store) =>
{
Order[] all = store.Query(query.Sku);
Order[] page = all.Skip((query.PageOrDefault - 1) * query.SizeOrDefault)
.Take(query.SizeOrDefault)
.ToArray();
return TypedResults.Ok(
new PagedResult<Order>(query.PageOrDefault, query.SizeOrDefault, all.Length, page));
})
.AddEndpointFilter<ValidationFilter<ListQuery>>()
.WithName("ListOrders");
orders.MapPost("", (CreateOrder body, OrderStore store) =>
{
Order created = store.Add(body.Sku, body.Quantity);
return TypedResults.Created("/api/orders/" + created.Id, created);
})
.AddEndpointFilter<ValidationFilter<CreateOrder>>()
.WithName("CreateOrder");
await app.StartAsync();
using HttpClient client = new HttpClient { BaseAddress = new Uri("http://127.0.0.1:5214") };
await Call(HttpMethod.Get, "/api/orders?page=1&pageSize=2");
await Call(HttpMethod.Get, "/api/orders?page=2&pageSize=2");
await Call(HttpMethod.Get, "/api/orders?page=0&pageSize=2");
await Call(HttpMethod.Get, "/api/orders?sku=NUT-07");
await Call(HttpMethod.Post, "/api/orders", new { sku = "", quantity = 0 });
await Call(HttpMethod.Post, "/api/orders", new { sku = "WASHER-3", quantity = 4 });
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);
Console.WriteLine(" " + Summarise(text));
}
// A problem document carries a "type" URI that differs between .NET versions,
// so only the per-field errors object is printed here.
static string Summarise(string json)
{
if (json.Length == 0)
{
return "(no body)";
}
using JsonDocument document = JsonDocument.Parse(json);
return document.RootElement.TryGetProperty("errors", out JsonElement errors)
? "errors " + errors.GetRawText()
: json;
}
record Order(int Id, string Sku, int Quantity);
record PagedResult<T>(int Page, int PageSize, int Total, T[] Items);
interface IValidatable
{
Dictionary<string, string[]> Validate();
}
record ListQuery(int? Page, int? PageSize, string? Sku) : IValidatable
{
public int PageOrDefault => Page ?? 1;
public int SizeOrDefault => PageSize ?? 2;
public Dictionary<string, string[]> Validate()
{
Dictionary<string, string[]> errors = new Dictionary<string, string[]>();
if (Page is < 1) // null matches neither pattern
{
errors["page"] = new[] { "page must be 1 or greater" };
}
if (PageSize is < 1 or > 50)
{
errors["pageSize"] = new[] { "pageSize must be 1-50" };
}
return errors;
}
}
record CreateOrder(string Sku, int Quantity) : IValidatable
{
public Dictionary<string, string[]> Validate()
{
Dictionary<string, string[]> errors = new Dictionary<string, string[]>();
if (string.IsNullOrWhiteSpace(Sku))
{
errors["sku"] = new[] { "sku is required" };
}
if (Quantity is < 1 or > 100)
{
errors["quantity"] = new[] { "quantity must be 1-100" };
}
return errors;
}
}
// One filter, reused for every endpoint whose input can describe its own rules.
sealed class ValidationFilter<T> : IEndpointFilter where T : class, IValidatable
{
public async ValueTask<object?> InvokeAsync(
EndpointFilterInvocationContext context, EndpointFilterDelegate next)
{
T? target = context.Arguments.OfType<T>().FirstOrDefault();
if (target is not null)
{
Dictionary<string, string[]> errors = target.Validate();
if (errors.Count > 0)
{
return TypedResults.ValidationProblem(errors); // short-circuits the endpoint
}
}
return await next(context);
}
}
sealed class OrderStore
{
private readonly List<Order> items = new List<Order>
{
new Order(1, "BOLT-01", 2),
new Order(2, "NUT-07", 5),
new Order(3, "BOLT-01", 1)
};
public Order[] Query(string? sku) =>
items.Where(o => sku is null || o.Sku == sku).ToArray();
public Order Add(string sku, int quantity)
{
Order created = new Order(items.Count + 1, sku, quantity);
items.Add(created);
return created;
}
}
Output:
200 GET /api/orders?page=1&pageSize=2
{"page":1,"pageSize":2,"total":3,"items":[{"id":1,"sku":"BOLT-01","quantity":2},{"id":2,"sku":"NUT-07","quantity":5}]}
200 GET /api/orders?page=2&pageSize=2
{"page":2,"pageSize":2,"total":3,"items":[{"id":3,"sku":"BOLT-01","quantity":1}]}
400 GET /api/orders?page=0&pageSize=2
errors {"page":["page must be 1 or greater"]}
200 GET /api/orders?sku=NUT-07
{"page":1,"pageSize":2,"total":1,"items":[{"id":2,"sku":"NUT-07","quantity":5}]}
400 POST /api/orders
errors {"sku":["sku is required"],"quantity":["quantity must be 1-100"]}
201 POST /api/orders
{"id":4,"sku":"WASHER-3","quantity":4}
One filter class serves both endpoints because the rules travel with the input type, not with the route. ValidationFilter<T> knows nothing about orders; it finds the argument of type T, asks it what is wrong, and either short-circuits with a problem document or lets the handler run. Middleware could not do this — it runs before binding and would have to parse the body itself — which is the practical reason endpoint filters exist.
The read endpoint is paged whether the client asks or not. pageSize defaults to a small number and is capped at 50, so no caller can ask for the whole table by accident, and the response carries total so a client can render a page count. Offset paging is chosen here for clarity; on a large, actively written table it drifts and slows down, and the keyset approach from the migrations lesson is the better tool.
The two 400 responses come from the same place but describe different failures: page zero is a bad filter, and the empty SKU with quantity zero is a bad write. In both cases the client gets a map of field names to messages, which is enough to highlight the offending input without parsing prose. The full response also carries the standard problem-details fields, and only the errors object is printed because the type URI it includes has changed between .NET releases.
WithName and WithTags are not decoration. The name is what LinkGenerator uses to build a URL for that endpoint without hard-coding the path, and the tag is what groups the endpoints in the generated OpenAPI document — both covered in the next lesson along with the controller-based alternative. As with every example in this module, nothing here checks who the caller is: these endpoints are open to anyone who can reach the port until the security module's authentication is added.
Common Mistakes
- Returning
200for everything. A create that answers200with noLocationheader forces the client to guess the new resource's URL, and a delete that answers200with an empty body is indistinguishable from a no-op. Choose201,204and404deliberately. - Two complex parameters on one endpoint. Only one parameter can come from the body, so a second complex type throws at startup unless it is bound from elsewhere. Combine them into one request record, or mark the other with
[FromServices]or[AsParameters]. - Unbounded list endpoints.
MapGet("/orders", (OrderStore s) => s.All())is fine with three rows and fatal with three million. Page from the first commit, cap the page size on the server, and never trust the client's number. - Doing validation inside the handler and returning strings.
return Results.BadRequest("bad quantity")gives a client nothing to bind to a form field. ReturnValidationProblemwith a field-keyed dictionary, and put the rules where they can be reused.
- Putting business logic in the lambda. A handler that grows past a few lines becomes untestable without HTTP and unreadable in
Program.cs. Move the work into an injected service and keep the handler as translation: bind, call, map the outcome to a result. - Ignoring
CancellationToken. Add it as a parameter and pass it down; without it, a client that disconnects leaves the server finishing an expensive query for nobody. It binds automatically fromHttpContext.RequestAborted. - Leaking domain entities as the response shape. Returning an EF entity serialises whatever navigation properties happen to be loaded, exposes internal columns, and turns a database rename into a breaking API change. Project to a response record.
- Assuming a route constraint validates input.
{id:int}only decides whether the route matches, so a non-numeric id produces404, not400. Anything the client should be told about explicitly needs a real check with a real message.
Best Practices
- Group a resource with
MapGroup, and attach shared filters, tags and authorisation to the group rather than repeating them on every endpoint. - Use
TypedResultsand declare unions such asResults<Ok<Order>, NotFound>, so the endpoint's contract is checked by the compiler and picked up by OpenAPI for free. - Keep request and response records separate from domain types, even when they look identical today. They change for different reasons.
- Page every collection endpoint, cap the page size on the server, and return the total so clients do not have to fetch pages to discover how many there are.
- Put validation in a filter keyed on the input type, so one implementation covers every endpoint and the rules live next to the data they describe.
- Name endpoints with
WithNameand build URLs withLinkGeneratorinstead of string-concatenating paths that a later route change will silently break. - Return problem details for every failure, with a stable shape and a correlation id, so client error handling can be written once.
- Move handlers out of
Program.csinto static methods or a smallMapOrders(this IEndpointRouteBuilder)extension per resource once there are more than a handful.
Practice Exercises
- Finish the resource. Add
GET /api/orders/{id:int}returningResults<Ok<Order>, NotFound>andDELETE /api/orders/{id:int}returning204or404. Drive both the found and the missing case through the in-process client and print the status codes. - Cap the page size honestly. Change
ListQueryso a request forpageSize=500is rejected with a field error rather than silently clamped, then argue in a comment for whichever behaviour you would ship and why a client would prefer it. - Write a timing filter. Add an endpoint filter to the group that measures each handler and adds an
X-Handler-Durationheader, and explain why the same job done in middleware would not know which endpoint it timed unless it ran afterUseRouting. - Bind a custom type. Give a
DateRangerecord a staticTryParseso?created=2026-01-01..2026-03-31binds as one parameter, use it to filter the list, and show a400for a malformed range instead of an exception.