📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What are endpoint filters in Minimal APIs? Write a reusable filter with IEndpointFilter, apply it to a route group, and explain how filter ordering works and what a filter can see and change.

Coding question on Minimal API endpoint filters: IEndpointFilter and inline AddEndpointFilter, EndpointFilterInvocationContext and argument access, short-circuiting with a result, applying filters to route groups, onion ordering of group and endpoint filters, filter factories, and when to use endpoint filters versus middleware or .NET 10 built-in validation.

Intermediate Coding Intermediate aspnet-core endpoint-filters minimal-apis request-handling route-groups

🎯 Key points

  • An endpoint filter wraps only the handler invocation, after routing and parameter binding
  • IEndpointFilter.InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) returns ValueTask<object?>
  • context.Arguments exposes the bound handler arguments; GetArgument<T>(index) reads them by position
  • Return a result (e.g. TypedResults.ValidationProblem) without calling next to short-circuit
  • Filters run in registration order on the way in and reverse on the way out; group filters run before endpoint filters
  • AddEndpointFilter<T>() resolves T with constructor DI; AddEndpointFilterFactory inspects the handler once at start-up so endpoints that don't need the filter pay nothing
  • Filters keep handler-aware concerns (idempotency, auditing, FluentValidation) separate from handlers and reusable across groups; keep them cheap because they run on every call to those endpoints
  • In .NET 10, AddValidation() already applies DataAnnotations to Minimal API parameters; a custom filter is still right for FluentValidation, custom rules or older target frameworks

⏱ 30-second answer

An endpoint filter is the Minimal API equivalent of an MVC action filter: it wraps the handler invocation after routing and parameter binding, so it can see the bound arguments through EndpointFilterInvocationContext.Arguments, run code before and after the handler, change the result, or short-circuit by returning a result without calling next. You implement IEndpointFilter (or pass a lambda to AddEndpointFilter) and attach it to an endpoint or a route group. Order is an onion: filters run in the order added on the way in and reverse on the way out, with group filters outside endpoint filters. AddEndpointFilterFactory lets you inspect the handler once at start-up and skip the filter where it isn't needed. The trade-off: filters are precise and cheap but only wrap Minimal API handlers; global concerns stay in middleware.

🗣 Full answer (senior)

How I would answer this in an interview

> "Endpoint filters came in .NET 7 to give Minimal APIs what action filters give controllers. Routing has already chosen the endpoint and binding has already produced the arguments, so a filter gets an EndpointFilterInvocationContext with the HttpContext and the Arguments list, plus a next delegate. It can inspect or replace arguments, call next to run the handler, and look at or replace the result. If it returns a result without calling next, the handler never runs, which is how a validation or feature-flag filter short-circuits. > > I write them as classes implementing IEndpointFilter so they get constructor injection and can be unit tested, and I attach them to a route group so a whole feature gets them, including endpoints added later. Ordering is an onion: the first filter added is outermost. Group filters wrap endpoint filters, and nested groups wrap inner ones. For generic filters I like AddEndpointFilterFactory: it runs once at start-up with the handler's MethodInfo, so a validation filter can find which argument position holds the DTO and return next unchanged for endpoints that don't need it, which costs nothing per request. > > The mistake I see is using filters for things that should apply to every request, like correlation IDs. Filters only run for matched Minimal API endpoints, not for 404s, static files or controllers. And in .NET 10, I don't write a DataAnnotations validation filter any more because AddValidation() does it; filters are for FluentValidation, idempotency keys, auditing and similar handler-aware concerns."


What a filter can do

Action How
Read arguments `context.GetArgument

🔍 What the interviewer is checking

Checks practical Minimal API skills: writing a correct, reusable filter and understanding where it runs.

Green flags

  • Knows filters run after binding and can short-circuit.
  • Applies filters to route groups and explains ordering.
  • Uses a factory or type search instead of hard-coded argument indexes.
  • Knows when middleware or built-in validation is better.

Red flags

  • Thinks endpoint filters run for every request.
  • Hard-codes GetArgument<T>(0) in a generic filter.
  • Writes a DataAnnotations filter in .NET 10 without mentioning AddValidation().

📚 Learn in depth

1. Where filters sit

Routing ─► Endpoint RequestDelegate
             ├─ bind parameters (route, query, body, services)
             ├─ build EndpointFilterInvocationContext(arguments)
             ├─ filter 1 ─► filter 2 ─► ... ─► handler
             └─ write result (IResult.ExecuteAsync or JSON)

Binding failures (400) happen before filters, so a filter never sees an unbindable request.

2. The pipeline is built once

When the endpoint is built, the RequestDelegateFactory composes all filters into one EndpointFilterDelegate. Each AddEndpointFilter registers an EndpointFilterFactory delegate in the endpoint's builder conventions. Factories run once at start-up with an EndpointFilterFactoryContext exposing MethodInfo and services, and return the per-request delegate.

3. Arguments

EndpointFilterInvocationContext.Arguments is an IList<object?> in handler parameter order. Generic DefaultEndpointFilterInvocationContext<T1..Tn> avoids boxing in generated code; GetArgument<T> reads typed values. Services and CancellationToken are arguments too.

4. Results

next returns object?: either an IResult or the handler's raw return value (which will be JSON-serialised). Filters that wrap results must handle both.

5. DI and lifetime

AddEndpointFilter<TFilter>() creates the filter with ActivatorUtilities per request using request services, so scoped dependencies are fine. Inline lambdas are simplest but harder to test.

6. Compared with .NET 10 validation

AddValidation() itself is implemented as an endpoint filter added by convention. Calling .DisableValidation() on an endpoint removes it.

Try it yourself

  1. Add three logging filters to a group and an endpoint and print the in/out order.
  2. Write a filter that rejects requests when a feature flag is off and test it with WebApplicationFactory.
  3. Use AddEndpointFilterFactory to attach a FluentValidation filter only to handlers that have a parameter with a registered IValidator<T>.
  4. Replace an argument (normalise an email to lower case) in a filter and confirm the handler sees it.
  5. Unit test an IEndpointFilter by constructing DefaultEndpointFilterInvocationContext directly.

💻 Code

A reusable FluentValidation endpoint filter built with a factory so it only runs where a validator exists, plus an idempotency filter on a route group.

// Filters/ValidationFilterFactory.cs
using System.Reflection;
using FluentValidation;

namespace Payments.Api.Filters;

public static class ValidationFilterFactory
{
    // Runs ONCE per endpoint at start-up: find which argument needs validating
    public static EndpointFilterDelegate Create(EndpointFilterFactoryContext factoryContext, EndpointFilterDelegate next)
    {
        var parameters = factoryContext.MethodInfo.GetParameters();
        var services = factoryContext.ApplicationServices;
        var targets = parameters
            .Select((p, index) => (Index: index, ValidatorType: typeof(IValidator<>).MakeGenericType(p.ParameterType)))
            .Where(t => services.GetService(typeof(IServiceProviderIsService)) is IServiceProviderIsService isService
                        && isService.IsService(t.ValidatorType))
            .ToArray();

        if (targets.Length == 0) return next;          // nothing to validate: zero per-request cost

        return async invocation =>
        {
            foreach (var (index, validatorType) in targets)
            {
                var validator = (IValidator)invocation.HttpContext.RequestServices.GetRequiredService(validatorType);
                var argument = invocation.Arguments[index];
                if (argument is null) continue;
                var result = await validator.ValidateAsync(new ValidationContext<object>(argument),
                    invocation.HttpContext.RequestAborted);
                if (!result.IsValid) return TypedResults.ValidationProblem(result.ToDictionary()); // short-circuit
            }
            return await next(invocation);
        };
    }
}

// Idempotency: repeated keys get the original outcome instead of a second charge
public sealed class IdempotencyFilter(IIdempotencyStore store) : IEndpointFilter
{
    public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
    {
        var key = context.HttpContext.Request.Headers["Idempotency-Key"].ToString();
        if (string.IsNullOrWhiteSpace(key))
            return TypedResults.Problem("Idempotency-Key header is required.", statusCode: StatusCodes.Status400BadRequest);

        if (await store.TryGetAsync(key, context.HttpContext.RequestAborted) is { } previous)
            return TypedResults.Ok(previous);

        var result = await next(context);
        await store.SaveAsync(key, result, context.HttpContext.RequestAborted);
        return result;
    }
}

public interface IIdempotencyStore
{
    Task<object?> TryGetAsync(string key, CancellationToken ct);
    Task SaveAsync(string key, object? result, CancellationToken ct);
}
// Program.cs
using FluentValidation;
using Payments.Api.Filters;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IValidator<CreatePayment>, CreatePaymentValidator>();
builder.Services.AddSingleton<IIdempotencyStore, RedisIdempotencyStore>();
var app = builder.Build();

var payments = app.MapGroup("/payments")
    .AddEndpointFilter<IdempotencyFilter>()                 // outermost: runs first, sees final result last
    .AddEndpointFilterFactory(ValidationFilterFactory.Create);

payments.MapPost("/", (CreatePayment cmd) => TypedResults.Ok(new { Id = Guid.NewGuid(), cmd.AmountCents }));
app.Run();

public sealed record CreatePayment(string AccountId, long AmountCents);
public sealed class CreatePaymentValidator : AbstractValidator<CreatePayment>
{
    public CreatePaymentValidator()
    {
        RuleFor(x => x.AccountId).NotEmpty();
        RuleFor(x => x.AmountCents).InclusiveBetween(1, 10_000_000);
    }
}

⚠ Common mistakes

  • Mistake: Using endpoint filters for concerns every request needs. Why it is wrong: They only run for matched Minimal API endpoints, not 404s, static files or controllers. Instead: Use middleware for global concerns.
  • Mistake: Hand-writing a DataAnnotations validation filter for a .NET 10 Minimal API by default. Why it is wrong: AddValidation() already validates DataAnnotations (nested objects and collections included) with source generation and a standard ProblemDetails 400, so a custom filter duplicates it and can drift in error shape. Instead: Use the built-in validation; DataAnnotations themselves remain the right tool. Write a custom filter when you need FluentValidation, rules DataAnnotations can't express, a different error contract, or you target .NET 8/9.
  • Mistake: Reading arguments by fixed index in a generic filter. Why it is wrong: Parameter order differs per handler, so the filter breaks or validates the wrong value. Instead: Find positions in a filter factory from MethodInfo, or search by type.
  • Mistake: Assuming next returns an IResult. Why it is wrong: It returns the handler's raw value when the handler returns a DTO. Instead: Handle both IResult and plain objects when wrapping results.
  • Mistake: Adding filters in the wrong order. Why it is wrong: An auditing filter outside a validation filter records rejected requests. Instead: Remember the onion: first added is outermost.
  • Mistake: Doing expensive reflection or I/O per request in a filter. Why it is wrong: It adds allocations, CPU and latency to every call on the group. Instead: Do reflection once in AddEndpointFilterFactory, cache lookups, and measure with a load test if the filter sits on a hot path.

🏛 Senior insight: trade-offs

Endpoint filters are the right place for concerns that depend on the handler: its arguments, its result, or its metadata. The factory form is the senior touch: decide at start-up whether a filter applies, so endpoints that don't need it pay nothing. Keep the global pipeline in middleware and lean on built-in features (validation, output caching, rate limiting, auth policies) before writing a filter.

Option When it fits Cost When not to
IEndpointFilter class Reusable, testable handler-aware logic One class Trivial one-offs
Inline lambda filter Small, endpoint-specific logic Hard to test Shared behaviour
AddEndpointFilterFactory Generic filters that depend on handler signature Reflection at start-up Simple filters
Middleware Every request No access to arguments Handler-specific logic
Built-in (AddValidation, CacheOutput, RequireRateLimiting) Common needs None When you need custom behaviour

🔗 Follow-ups the interviewer may ask

  1. When: Candidate compares endpoint filters with action filters. Why: Checks the MVC counterpart and how endpoint filters differ from action filters.
    How to answer

    MVC filters run inside the MVC action invoker, around specific stages of an action. Authorisation filters run first and can short-circuit; resource filters wrap model binding and everything after, so they suit caching or rejecting early; action filters run just before and after the action and can see and change the bound arguments and result; exception filters handle exceptions from the action and action filters; result filters wrap the execution of the result, e.g. adding headers. Ordering is by scope (global → controller → action on the way in, reversed on the way out) unless Order says otherwise. I use a filter instead of middleware when the logic needs MVC context: the action, its arguments or ModelState. Middleware is for things true of every request. The trade-off: filters are precise but MVC-only.

  2. When: Candidate writes a validation filter. Why: Checks overall validation strategy including .NET 10 AddValidation and FluentValidation.
    How to answer

    I validate input at the edge and business rules in the application or domain layer. For input, DataAnnotations ([Required], [Range], [StringLength]) and IValidatableObject on request DTOs are the baseline. In controllers, binding fills ModelState and [ApiController] returns a 400 ValidationProblemDetails before the action runs. In Minimal APIs on .NET 10, builder.Services.AddValidation() uses a source generator to validate parameters and return the same 400 ProblemDetails; before .NET 10 you needed a filter. FluentValidation is my choice for complex, conditional or async rules; I call it explicitly or from a filter, because its automatic MVC integration is deprecated. Business rules like stock levels or uniqueness are checked where the data lives and returned in the same error shape. The trade-off: attributes are simple and visible in OpenAPI; code-based validators are more expressive.

↩ Usually asked after

More in Request Handling

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me