Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk
Last active September 8, 2024 01:28
Show Gist options
  • Save dj-nitehawk/3edcd59ce03230b98369e2f2259bc5d3 to your computer and use it in GitHub Desktop.
Save dj-nitehawk/3edcd59ce03230b98369e2f2259bc5d3 to your computer and use it in GitHub Desktop.
IEndpointFilter usage in FastEndpoints
sealed class OperationCancelledFilter : IEndpointFilter
{
private readonly ILogger<OperationCancelledFilter> logger;
public OperationCancelledFilter(ILogger<OperationCancelledFilter> logger)
{
this.logger = logger;
}
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
{
try
{
return await next(context);
}
catch (OperationCanceledException x)
{
logger.LogDebug(x, "Request was cancelled!");
return Results.StatusCode(499);
}
}
}
// to only apply the filter to a certain endpoint
public override void Configure()
{
Post("order/create");
Options(x => x.AddEndpointFilter<OperationCancelledFilter>());
}
// to apply the filter globally to all endpoints
app.UseFastEndpoints(c => c.Endpoints.Configurator = ep =>
{
ep.Options(b => b.AddEndpointFilter<OperationCancelledFilter>());
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment