Add an Application layer #2
30
Application/Common/Behaviors/ValidationBehavior.cs
Normal file
30
Application/Common/Behaviors/ValidationBehavior.cs
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
using FluentValidation;
|
||||||
|
using MediatR;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace Mirea.Api.DataAccess.Application.Common.Behaviors;
|
||||||
|
|
||||||
|
public class ValidationBehavior<TRequest, TResponse>(IEnumerable<IValidator<TRequest>> validators)
|
||||||
|
: IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>
|
||||||
|
{
|
||||||
|
public Task<TResponse> Handle(TRequest request,
|
||||||
|
RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var context = new ValidationContext<TRequest>(request);
|
||||||
|
var failures = validators
|
||||||
|
.Select(v => v.Validate(context))
|
||||||
|
.SelectMany(result => result.Errors)
|
||||||
|
.Where(failure => failure != null)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
if (failures.Count != 0)
|
||||||
|
{
|
||||||
|
throw new ValidationException(failures);
|
||||||
|
}
|
||||||
|
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user