gotchacsharpdotnetMajor
ASP.NET Core minimal API route handlers don't inherit controller filters
Viewed 0 times
.NET 7+
minimal api filtersRequireAuthorizationendpoint filterIEndpointFilterglobal exception handler minimal api
Problem
Developers coming from controller-based APIs expect global filters (authorization, exception handling, model validation) to apply automatically to minimal API endpoints. They do not. Minimal APIs have a separate filter pipeline and attribute-based filters like [Authorize] work differently.
Solution
Use endpoint-level extensions to apply policies. Authorization uses RequireAuthorization(), rate limiting uses RequireRateLimiting(), etc.:
For endpoint filters (like model validation) use IEndpointFilter:
app.MapGet("/secure", () => "secret")
.RequireAuthorization("AdminPolicy")
.RequireRateLimiting("fixed");
// Global exception handling: use app.UseExceptionHandler() middleware
// or IExceptionHandler registered in DI
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
app.UseExceptionHandler();For endpoint filters (like model validation) use IEndpointFilter:
app.MapPost("/items", (Item item) => Results.Ok(item))
.AddEndpointFilter<ValidationFilter<Item>>();Why
Minimal APIs were designed as a lightweight alternative that bypasses the MVC pipeline entirely. The MVC filter pipeline (IActionFilter, IResultFilter, etc.) is coupled to ControllerBase and does not participate in the minimal API routing layer.
Gotchas
- app.UseAuthorization() middleware must still be added for RequireAuthorization() to work
- FluentValidation's automatic validation middleware targets MVC — wire it manually for minimal APIs
- Exception filters on controllers don't catch exceptions from minimal API handlers
Revisions (0)
No revisions yet.