skip to content

In an ASP.NET Core Minimal API, what does a timing endpoint filter on the /api/v1/fleet group measure, and can it still set a response header after next returns?

level: seniorimportance: nice to knowfreq 20%

answer

  1. after binding, before writing
  2. inner filters plus handler
  3. result executed after the chain returns
  4. Response.HasStarted before setting headers
  5. binding failure: 400 already set

basics

~20 s

It times the inner filters and the handler with its awaited work, not routing, binding or serialization; the result is written after the filter chain returns, so a header set after next is still sent unless the handler wrote the response itself.

solid answer

~50 s

An endpoint filter runs inside the endpoint's request delegate, after parameter binding (route values parsed, the JSON body read and deserialized, services resolved) and before the result is executed. A `Stopwatch` around `await next(context)` therefore times the inner filters and the handler, including everything it awaits, and excludes middleware, routing, binding and the response write. Because the handler's result (an `IResult`, a string or an object to serialize) is only executed after the outermost filter returns, the response has normally not started when `next` returns, so `HttpContext.Response.Headers` can still be set; check `Response.HasStarted` for handlers that write to the response themselves. Outside Development, a route or query value that fails to bind sets status 400 and the filters still run while the handler is skipped; in Development `ThrowOnBadRequest` throws before any filter runs, and an unreadable JSON body ends the request before filters in both.

code

csharp · 26 lines
csharp
using System.Diagnostics;

var fleet = app.MapGroup("/api/v1/fleet").AddEndpointFilter<TimingFilter>();

public sealed class TimingFilter(ILogger<TimingFilter> logger) : IEndpointFilter
{
    public async ValueTask<object?> InvokeAsync(
        EndpointFilterInvocationContext context, EndpointFilterDelegate next)
    {
        var start = Stopwatch.GetTimestamp();
        try
        {
            return await next(context);
        }
        finally
        {
            var elapsed = Stopwatch.GetElapsedTime(start);
            if (!context.HttpContext.Response.HasStarted)
            {
                context.HttpContext.Response.Headers["X-Handler-Ms"] =
                    elapsed.TotalMilliseconds.ToString("F1");
            }
            logger.LogInformation("Handled in {ElapsedMs} ms", elapsed.TotalMilliseconds);
        }
    }
}

go deeper

for a junior

Recall that an endpoint filter runs around the handler after its parameters are bound, and that it can add a response header after next returns.

for a middle

Explain the order inside the endpoint delegate (bind, filters, handler, write the result), and why headers stay writable after next unless the handler wrote the response.

for a senior

Read timing data correctly: filter timings exclude binding and serialization, near-zero 400s are binding failures outside Development, and whole-request latency belongs to middleware or the request duration metric.

for a principal

Decide which latency each layer reports and label it: handler time from filters, request time from server metrics, so dashboards and alerts never mix the two.

## Where the filter chain sits inside an endpoint For a Minimal API endpoint with filters, the endpoint's request delegate does this, in order: 1. **Binds parameters**: parses route, query and header values, reads and deserializes a JSON body, resolves services. 2. **Builds an `EndpointFilterInvocationContext`** holding the bound arguments. 3. **Invokes the filter chain**, outermost filter first; the innermost delegate calls the handler. 4. **Writes the result** that comes back out of the chain: executes an `IResult`, writes a `string` as `text/plain`, or serializes any other object as JSON. Middleware and routing happen before step 1, outside the endpoint altogether. ## What a group timing filter measures ```csharp using System.Diagnostics; public sealed class TimingFilter(ILogger<TimingFilter> logger) : IEndpointFilter { public async ValueTask<object?> InvokeAsync( EndpointFilterInvocationContext context, EndpointFilterDelegate next) { var start = Stopwatch.GetTimestamp(); try { return await next(context); } finally { var elapsed = Stopwatch.GetElapsedTime(start); if (!context.HttpContext.Response.HasStarted) { context.HttpContext.Response.Headers["X-Handler-Ms"] = elapsed.TotalMilliseconds.ToString("F1"); } logger.LogInformation("Handled in {ElapsedMs} ms", elapsed.TotalMilliseconds); } } } ``` Attached with `fleet.AddEndpointFilter<TimingFilter>()` as the first filter on the outermost group, the measured span: | Included | Excluded | |---|---| | every filter inside it (inner groups, endpoint filters) | middleware, authentication, routing | | the handler and all awaited work | parameter binding and JSON body deserialization | | exceptions until they leave the handler (the `finally` still runs) | executing the returned `IResult` or serializing the object | For whole-request latency, measure in middleware or use the built-in `http.server.request.duration` metric; a filter answers a narrower question: how long did the handler's own work take. ## Setting a header after `next` When `await next(context)` returns a `TypedResults.Ok(position)`, that result has **not** been executed yet; it is just an object travelling back up the chain. Headers are still writable, so the filter above can add `X-Handler-Ms`. Exceptions to watch: - A handler that takes `HttpResponse` and writes to it, or streams, may already have started the response; setting a header then throws `InvalidOperationException`. The `HasStarted` check avoids that. - If the header must cover the time until the response actually starts, set it from a `Response.OnStarting` callback instead. ## Requests that never reach the handler - **A route, query or header value that fails to bind**, outside Development: the delegate sets `StatusCode = 400`, still runs the filter chain, and the innermost delegate skips the handler because the status is already 400 or more. The timing filter logs a near-zero duration with a 400. - **In Development**, `RouteHandlerOptions.ThrowOnBadRequest` is `true`, so the same failure throws `BadHttpRequestException` during binding and no filter runs. - **A malformed JSON body** (or a non-JSON content type, answered with 415) ends the request inside binding in every environment; no filter runs. - **A short-circuiting inner filter** still returns through the timing filter, which records it. - **A request that matches no endpoint** never reaches any endpoint filter. ## What interviewers listen for - The four steps inside the endpoint delegate: bind, build the invocation context, run the filters and handler, write the result. - That headers are writable after `next` because the result has not been executed, with the `HasStarted` caveat. - The binding-failure path and how it differs between Development and other environments. - Which number a filter can honestly report (handler time) and which it cannot (request latency).

  • Outside Development, why does a timing filter log a near-zero duration with status 400 for /api/v1/fleet/trucks/abc when the route is {truckId} and the handler takes int truckId?
    "abc" fails `int` parsing during binding. With filters present, the request delegate sets status 400 but still invokes the filter chain; the innermost delegate sees a status of 400 or more and returns an empty result without calling the handler. The filter therefore wraps almost no work. With a `{truckId:int}` constraint the request would not match the route at all.
  • How would you include result serialization in the measured time without moving the timer to middleware?
    Start the timer in the filter and stop it in a `Response.OnStarting` callback registered before calling `next`. The callback fires just before the headers are sent, when the result begins writing, so the measured span covers handler plus the start of serialization, and the header can still be added there.

  • A filter's stopwatch includes model binding and JSON body deserialization.
  • By the time next returns, the result is serialized, so headers are read-only.
  • Binding failures always return 400 before any endpoint filter runs.
  • Endpoint filters time the whole request, middleware and routing included.
  • A timing filter on the group also records requests that matched no endpoint.