dev
Line | |
---|
1 | using FluentValidation;
|
---|
2 | using MediatR;
|
---|
3 | using FinkiChattery.Common.Errors.Exceptions;
|
---|
4 | using System.Collections.Generic;
|
---|
5 | using System.Threading;
|
---|
6 | using System.Threading.Tasks;
|
---|
7 |
|
---|
8 | namespace 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.