Introduced `ValidationBehavior` to validate MediatR requests using FluentValidation. Registered the behavior in the pipeline and added validators for `ReadDocumentDetailsQuery` and `ReadDocumentQuery`. Updated dependency injection to include validators and added FluentValidation NuGet packages. Improved exception handling with `BadRequestException` for validation failures. Refactored namespaces and imports to support the changes.
41 lines
1.2 KiB
C#
41 lines
1.2 KiB
C#
using DigitalData.Core.Exceptions;
|
|
using FluentValidation;
|
|
using MediatR;
|
|
|
|
namespace EnvelopeGenerator.Application.Common.Behaviors;
|
|
|
|
public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
|
|
where TRequest : notnull
|
|
{
|
|
private readonly IEnumerable<IValidator<TRequest>> _validators;
|
|
|
|
public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators)
|
|
{
|
|
_validators = validators;
|
|
}
|
|
|
|
public async Task<TResponse> Handle(
|
|
TRequest request,
|
|
RequestHandlerDelegate<TResponse> next,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
if (_validators.Any())
|
|
{
|
|
var context = new ValidationContext<TRequest>(request);
|
|
var failures = _validators
|
|
.Select(v => v.Validate(context))
|
|
.SelectMany(r => r.Errors)
|
|
.Where(f => f is not null)
|
|
.ToList();
|
|
|
|
if (failures.Count > 0)
|
|
{
|
|
var message = string.Join("; ", failures.Select(f => f.ErrorMessage).Distinct());
|
|
throw new BadRequestException(message);
|
|
}
|
|
}
|
|
|
|
return await next();
|
|
}
|
|
}
|