Last active
September 8, 2024 01:28
-
-
Save dj-nitehawk/3edcd59ce03230b98369e2f2259bc5d3 to your computer and use it in GitHub Desktop.
IEndpointFilter usage in FastEndpoints
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// to only apply the filter to a certain endpoint | |
public override void Configure() | |
{ | |
Post("order/create"); | |
Options(x => x.AddEndpointFilter<OperationCancelledFilter>()); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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