.NET Minimal API Endpoint Filters Middleware
EndpointFilters in .NET Minimal APIs are a great way to run operations before or after your minimal api is executed.
You can even inject registered services into endpoint filter classes.
Creating an Endpoint Filter
To get started, create a new class that extends IEndpointFilter.
This class needs 1 method to satisfy the IEndpointFilter interface, InvokeAsync. This is where your logic will go. For this example, we will get the logged in user and test if their account is setup.
If not, we will redirect them to the account-setup page.
public class IsAccountSetupFilter : IEndpointFilter
{
private readonly AuthService _authService;
public IsAccountSetupFilter(AuthService authService)
{
_authService = authService;
}
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
{
var user = await _authService.GetAuthenticatedUser(context.HttpContext.User);
// if users account isn't setup, redirect to account-setup
if (!user.IsSetup)
{
return Results.Redirect("/account-setup/create");
}
// else carry on with request
return await next(context);
}
}
Attaching the Filter to a Minimal API Endpoint
Now we can attach this filter to any Minimal API endpoint in our application.
A great way to abstract code we would otherwise have to run manually in each one of our Minimal Api endpoints implementation.
app.MapGet("", new DashboardHandler().Index)
.AddEndpointFilter<IsAccountSetupFilter>();