38 lines
1.3 KiB
C#
38 lines
1.3 KiB
C#
using System.Threading.Tasks;
|
|
using FluentValidation;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
namespace Svrnty.CQRS.MinimalApi;
|
|
|
|
public class ValidationFilter<T> : IEndpointFilter where T : class
|
|
{
|
|
public const string ValidatedObjectKey = "ValidatedObject";
|
|
|
|
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
|
|
{
|
|
// Deserialize the request body
|
|
var obj = await context.HttpContext.Request.ReadFromJsonAsync<T>(context.HttpContext.RequestAborted);
|
|
|
|
if (obj == null)
|
|
return Results.BadRequest("Invalid request payload");
|
|
|
|
// Store the deserialized object for the lambda to retrieve
|
|
context.HttpContext.Items[ValidatedObjectKey] = obj;
|
|
|
|
// Validate if validator is registered
|
|
var validator = context.HttpContext.RequestServices.GetService<IValidator<T>>();
|
|
if (validator != null)
|
|
{
|
|
var validationResult = await validator.ValidateAsync(obj, context.HttpContext.RequestAborted);
|
|
|
|
if (!validationResult.IsValid)
|
|
{
|
|
return Results.ValidationProblem(validationResult.ToDictionary());
|
|
}
|
|
}
|
|
|
|
return await next(context);
|
|
}
|
|
}
|