source: src/FinkiChattery/FinkiChattery.Common/Validation/ValidationBehavior.cs@ e6a6d9a

dev
Last change on this file since e6a6d9a was e6a6d9a, checked in by Стојков Марко <mst@…>, 3 years ago

Initialized FinkiChattery project

  • Property mode set to 100644
File size: 1.6 KB
Line 
1using FluentValidation;
2using MediatR;
3using FinkiChattery.Common.Errors.Exceptions;
4using System.Collections.Generic;
5using System.Threading;
6using System.Threading.Tasks;
7
8namespace FinkiChattery.Common.Validation
9{
10 public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
11 {
12 private readonly IEnumerable<IValidator<TRequest>> _validators;
13
14 public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators)
15 {
16 _validators = validators;
17 }
18
19 public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
20 {
21 var errors = new Dictionary<string, List<string>>();
22 var context = new ValidationContext<TRequest>(request);
23
24 foreach (var validation in _validators)
25 {
26 var validationResponse = await validation.ValidateAsync(context);
27
28 foreach (var error in validationResponse.Errors)
29 {
30 var errorProperty = errors.GetValueOrDefault(error.PropertyName);
31 if (errorProperty != null)
32 {
33 errorProperty.Add(error.ErrorMessage);
34 }
35 else
36 {
37 errors.Add(error.PropertyName, new List<string>() { error.ErrorMessage });
38 }
39 }
40 }
41
42 if (errors.Count > 0)
43 {
44 throw new BadRequestException(errors);
45 }
46
47 return await next();
48 }
49 }
50}
Note: See TracBrowser for help on using the repository browser.