This commit is contained in:
commit
1199bef0c8
3 changed files with 1200 additions and 0 deletions
15
src/Utils/RequestLoggingFilter.cs
Executable file
15
src/Utils/RequestLoggingFilter.cs
Executable file
|
|
@ -0,0 +1,15 @@
|
|||
namespace TestWeb.Utils;
|
||||
|
||||
public class RequestLoggingFilter(ILogger<RequestLoggingFilter> logger) : IEndpointFilter
|
||||
{
|
||||
public async ValueTask<object?> InvokeAsync(
|
||||
EndpointFilterInvocationContext context,
|
||||
EndpointFilterDelegate next)
|
||||
{
|
||||
logger.LogInformation(
|
||||
"HTTP {Method} {Path} recieved",
|
||||
context.HttpContext.Request.Method,
|
||||
context.HttpContext.Request.Path);
|
||||
return await next(context);
|
||||
}
|
||||
}
|
||||
34
src/Utils/RequestValidationFilter.cs
Executable file
34
src/Utils/RequestValidationFilter.cs
Executable file
|
|
@ -0,0 +1,34 @@
|
|||
namespace TestWeb.Utils;
|
||||
|
||||
public class RequestValidationFilter<TRequest>(
|
||||
ILogger<RequestValidationFilter<TRequest>> logger,
|
||||
IValidator<TRequest>? validator = null) : IEndpointFilter
|
||||
{
|
||||
public async ValueTask<object?> InvokeAsync(
|
||||
EndpointFilterInvocationContext context,
|
||||
EndpointFilterDelegate next)
|
||||
{
|
||||
var requestName = typeof(TRequest).FullName;
|
||||
|
||||
if (validator is null)
|
||||
{
|
||||
logger.LogInformation("{Request}: No validator configured.", requestName);
|
||||
return await next(context);
|
||||
}
|
||||
|
||||
logger.LogInformation("{Request}: Validating...", requestName);
|
||||
var request = context.Arguments.OfType<TRequest>().First();
|
||||
var validationResult = await validator.ValidateAsync(
|
||||
request,
|
||||
context.HttpContext.RequestAborted
|
||||
);
|
||||
if (!validationResult.IsValid)
|
||||
{
|
||||
logger.LogWarning("{Request}: Validation failed.", requestName);
|
||||
return TypedResults.ValidationProblem(validationResult.ToDictionary());
|
||||
}
|
||||
|
||||
logger.LogInformation("{Request}: Validation succeeded.", requestName);
|
||||
return await next(context);
|
||||
}
|
||||
}
|
||||
12
src/Utils/ValidationExtensions.cs
Executable file
12
src/Utils/ValidationExtensions.cs
Executable file
|
|
@ -0,0 +1,12 @@
|
|||
namespace TestWeb.Utils;
|
||||
|
||||
public static class ValidationExtensions
|
||||
{
|
||||
public static RouteHandlerBuilder WithRequestValidation<TRequest>(
|
||||
this RouteHandlerBuilder builder)
|
||||
{
|
||||
return builder
|
||||
.AddEndpointFilter<RequestValidationFilter<TRequest>>()
|
||||
.ProducesValidationProblem();
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue