ASP.NET Core middleware vs MVC filters vs endpoint filters

C# Language Interview Q&A November 13, 2026 csharp

Middleware: runs for every request, generic (logging, exception handling, headers).

csharp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// ======================================================================
// Q: Middleware vs filters?
//
// - Middleware: runs for every request, generic (logging, exception handling,
//   headers). It does not know which action will run.
// - Filters (MVC): inside the MVC pipeline, with access to action arguments,
//   ModelState and the result. Order: Authorization → Resource → Action →
//   Exception → Result.
// - Endpoint filters: the equivalent for Minimal APIs.
// ======================================================================

public class TimingMiddleware(RequestDelegate next, ILogger<TimingMiddleware> log)
{
    public async Task InvokeAsync(HttpContext ctx)
    {
        var sw = Stopwatch.StartNew();
        await next(ctx);                       // next in the chain
        log.LogInformation("{Path} took {Ms} ms", ctx.Request.Path, sw.ElapsedMilliseconds);
    }
}