I have a MediatR Pipeline behavior for validating commands with the FluentValidation library. I've seen many examples where you throw a ValidationException from the behavior, and that works fine for me. However in my scenario I want to update my response object with the validation errors.
I am able to build and run the following code. When I set a break point within the if statement the CommandResponse is constructed with the validation errors as expected - but when the response is received by the original caller it is null:
Код: Выделить всё
public class RequestValidationBehavior : IPipelineBehavior where TRequest : IRequest { private readonly IEnumerable _validators; public RequestValidationBehavior(IEnumerable validators) { _validators = validators; } public Task Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate next) { var context = new ValidationContext(request); // Run the associated validator against the request var failures = _validators .Select(v => v.Validate(context)) .SelectMany(result => result.Errors) .Where(f => f != null) .ToList(); if(failures.Count != 0) { var commandResponse = new CommandResponse(failures) { isSuccess = false }; return commandResponse as Task; } else { return next(); } } } Источник: https://stackoverflow.com/questions/541 ... e-behavior
Мобильная версия