skip to content

In ASP.NET Core Minimal APIs, in what order do endpoint filters on an outer group, an inner group and the endpoint itself run?

level: middleimportance: should knowfreq 45%

answer

  1. an onion, not a queue
  2. before next: first in, first out
  3. after next: first in, last out
  4. outer group, inner group, endpoint
  5. no Order property on endpoint filters

basics

~20 s

Outer group filters run first, then inner group filters, then the endpoint's own, whatever order the AddEndpointFilter calls appear in across those builders. On one builder, code before next runs in registration order and code after next in reverse.

solid answer

~40 s

Endpoint filters form an onion around the handler. On a single builder, the code before `await next(context)` runs in registration order (first in, first out) and the code after it runs in reverse (first in, last out). Across builders, scope decides: an outer group's conventions are applied to an endpoint before an inner group's, and both before the endpoint's own, so outer group filters wrap inner group filters, which wrap endpoint filters. Calling `inner.AddEndpointFilter(...)` before `outer.AddEndpointFilter(...)` in Program.cs does not change that. Endpoint filters have no `Order` property (that is MVC's `IOrderedFilter`), so to move a filter you register it earlier on the same builder or attach it to an enclosing group.

code

csharp · 18 lines
csharp
var fleet = app.MapGroup("/api/v1/fleet");
var trucks = fleet.MapGroup("/trucks");

trucks.AddEndpointFilter(Log("inner group"));
fleet.AddEndpointFilter(Log("outer group"));

trucks.MapGet("/{truckId:int}", (int truckId) => TypedResults.Ok(truckId))
      .AddEndpointFilter(Log("endpoint A"))
      .AddEndpointFilter(Log("endpoint B"));

static Func<EndpointFilterInvocationContext, EndpointFilterDelegate, ValueTask<object?>> Log(string name) =>
    async (ctx, next) =>
    {
        Console.WriteLine($"before {name}");
        var result = await next(ctx);
        Console.WriteLine($"after {name}");
        return result;
    };

go deeper

for a junior

Recall that filters wrap the handler like layers: the first one registered runs first on the way in and last on the way out.

for a middle

Explain why outer group filters run before inner group and endpoint filters regardless of call order, and how the list of filter factories is folded from last to first.

for a senior

Place cross-cutting filters deliberately: timing and auditing at the outermost group so they see short-circuits, guards near the endpoints they protect, and no reliance on Program.cs call order across groups.

for a principal

Treat filter placement as an API convention the team can audit: one outer layer per concern, documented, rather than per-endpoint stacks whose order nobody can reconstruct.

## The onion on one builder Every `AddEndpointFilter` and `AddEndpointFilterFactory` call adds a factory to the endpoint's `FilterFactories` list (the `AddEndpointFilter` overloads are thin wrappers over `AddEndpointFilterFactory`). When the endpoint is built, the framework walks that list **from last to first**, wrapping the handler each time, so the first-registered filter ends up **outermost**. For filters A then B on one endpoint: - before-`next` code: A, then B, then the handler (**first in, first out**); - after-`next` code: B, then A (**first in, last out**). ## Across groups and the endpoint Group conventions are applied to an endpoint before the endpoint's own conventions, and an outer group's before an inner group's. Since a filter is just a convention that appends to `FilterFactories`, the list for an endpoint ends up ordered **outer group, inner group, endpoint**, and the onion follows that order. The order of the calls in `Program.cs` only matters among filters on the **same** builder. One framework filter sits outside this rule. In ASP.NET Core 10, when `builder.Services.AddValidation()` is registered and the endpoint has not opted out, the framework inserts its validation filter factory at the **front** of the list once the group and endpoint conventions have run, so it wraps the group and endpoint filters you added. ## A worked trace ```csharp var fleet = app.MapGroup("/api/v1/fleet"); var trucks = fleet.MapGroup("/trucks"); trucks.AddEndpointFilter(Log("inner group")); fleet.AddEndpointFilter(Log("outer group")); // added later, still outermost trucks.MapGet("/{truckId:int}", (int truckId) => TypedResults.Ok(truckId)) .AddEndpointFilter(Log("endpoint A")) .AddEndpointFilter(Log("endpoint B")); static Func<EndpointFilterInvocationContext, EndpointFilterDelegate, ValueTask<object?>> Log(string name) => async (ctx, next) => { Console.WriteLine($"before {name}"); var result = await next(ctx); Console.WriteLine($"after {name}"); return result; }; ``` A request to `/api/v1/fleet/trucks/7` prints: 1. before outer group 2. before inner group 3. before endpoint A 4. before endpoint B 5. (the handler runs) 6. after endpoint B 7. after endpoint A 8. after inner group 9. after outer group ## Short-circuits inside the onion If the inner group's filter returns a result without calling `next`, the endpoint filters and the handler never run, but the outer group's after-`next` code still runs and sees that result. A filter that measures or logs at the outermost layer therefore observes short-circuited requests too. ## Changing the order | You want | Do this | |---|---| | B before A on one endpoint | register B first on that builder | | a filter around everything in the API | attach it to the outermost group | | a filter closer to the handler | attach it to the endpoint or an inner group | There is **no `Order` property** on endpoint filters. `IOrderedFilter.Order` belongs to MVC's filter pipeline and has no effect here. Filters added through `AddEndpointFilterFactory` sit in the same list as plain filters and are ordered by the same rules. ## `Finally` conventions are not a way around it `IEndpointConventionBuilder.Finally` registers a convention that runs after the endpoint's other conventions, the endpoint's own `Finally` callbacks first, then inner groups', then the outer group's last. For a route handler endpoint, though, `Finally` runs **after** the request delegate (and its filter pipeline) has been built, so a filter factory added there is never wired in. `Finally` is for last-word metadata, not for filters. ## What interviewers listen for - First in, first out on the way in; first in, last out on the way out. - Scope beats call order: outer group, inner group, endpoint. - No `Order` property, and why `IOrderedFilter` does not apply. - Where to put a filter that must observe short-circuits: the outermost layer.

  • Can IEndpointConventionBuilder.Finally add a filter that runs outside every other filter?
    No. For a route handler endpoint, `Finally` conventions run after the request delegate and its filter pipeline have been built, so a factory added to `FilterFactories` there is never wired in. Use `Finally` for metadata that must have the last word; put an outermost filter on the outermost group instead.
  • If an inner group filter short-circuits, does the outer group filter still see the request?
    Yes. The outer filter called `next`, which reached the inner filter; the inner one returned a result without calling its own `next`. The endpoint filters and handler are skipped, but control returns to the outer filter's after-`next` code with that result, so outer timing or logging still covers the request.

A truck entering a depot passes the yard gate, then the bay checkpoint, then the loading dock, and leaves through them in reverse. Which checkpoint was built first does not matter; where it stands decides when the truck meets it.

  • On one endpoint, the last AddEndpointFilter call runs first.
  • Whichever group calls AddEndpointFilter first in Program.cs runs first.
  • Implement IOrderedFilter and set Order to sort endpoint filters.
  • Filters from AddEndpointFilterFactory always run before plain AddEndpointFilter filters.
  • After-next code runs in the same order as before-next code.

Assumes ASP.NET Core 10: the built-in validation filter that AddValidation inserts ahead of your filters is new in 10; the group and endpoint ordering itself is unchanged.