1 min read

Endpoint filters in .NET minimal APIs


Middleware for individual endpoints

Add a filter to log request timing:

Program.cs
app.MapGet("/items", GetItems)
    .AddEndpointFilter(async (context, next) =>
    {
        var sw = Stopwatch.StartNew();
        var result = await next(context);
        sw.Stop();
        context.HttpContext.Response.Headers.Append("X-Elapsed-Ms", sw.ElapsedMilliseconds.ToString());
        return result;
    });

Validation filter:

ValidationFilter.cs
app.MapPost("/items", CreateItem)
    .AddEndpointFilter<ValidationFilter<CreateItemRequest>>();

Filters run in order and can short-circuit the pipeline by returning early instead of calling next.