Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to show (AddProblemDetails) multiple validation error against single property using Fluent Validation & MediatR Pipeline Behaviour #184

Open
akbarbd opened this issue Sep 3, 2022 · 3 comments

Comments

@akbarbd
Copy link

akbarbd commented Sep 3, 2022

 x.Map<ValidationException>(ex => new ProblemDetails
        {
            Title = "input validation rules broken",
            Status = (int)ex.StatusCode,
            Detail = ex.Message,
            Type = "https://somedomain/input-validation-rules-error"
        });
@akbarbd akbarbd changed the title How to show multiple validation error against single property using Fluent Validation & MediatR Pipeline Behaviour How to show (AddProblemDetails) multiple validation error against single property using Fluent Validation & MediatR Pipeline Behaviour Sep 3, 2022
@akbarbd akbarbd closed this as completed Sep 4, 2022
@akbarbd akbarbd reopened this Sep 4, 2022
@akbarbd
Copy link
Author

akbarbd commented Sep 4, 2022

I am develop this way but multiple error is not showing and output is unreadable exception.

1 . Exception Inheritance Class

 public class ValidationException : Exception
{
    public IDictionary<string, string[]> Errors { get; } 
    public ValidationException(string message, int? code = null) : base(message, code: code)
    {
        Errors = new Dictionary<string, string[]>();
    }

    public ValidationException(IEnumerable<ValidationFailure> failures):this("One or more validation failures have occurred.")
    {
        Errors = failures
            .GroupBy(e => e.PropertyName, e => e.ErrorMessage)
            .ToDictionary(failureGroup => failureGroup.Key, failureGroup => failureGroup.ToArray());
    }
}

2. MediatR Pipeline Behavior

 public sealed class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
   where TRequest : class, IRequest<TResponse>
  {
      private readonly IEnumerable<IValidator<TRequest>> _validators;
      private readonly IServiceProvider _serviceProvider;

      public ValidationBehavior(IServiceProvider serviceProvider, IEnumerable<IValidator<TRequest>> validators)
      {
          _serviceProvider = serviceProvider;
          _validators = validators;
      }
      public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
      {
          if (_validators.Any())
          {
              var context = new ValidationContext<TRequest>(request);

              var validationResults = await Task.WhenAll(
                  _validators.Select(v =>
                      v.ValidateAsync(context, cancellationToken)));

              var failures = validationResults
                  .Where(r => r.Errors.Any())
                  .SelectMany(r => r.Errors)
                  .ToList();

              if (failures.Any())
                  throw new ValidationException(failures);
          }
          return await next();
      }
  }

3. ProblemDetailsExtensions

     public static IServiceCollection AddCustomProblemDetails(this IServiceCollection services)
      {
          services.AddProblemDetails(x =>
          {
               x.IncludeExceptionDetails = (ctx, _) =>
              {
                  // Fetch services from HttpContext.RequestServices
                  var env = ctx.RequestServices.GetRequiredService<IHostEnvironment>();
                  return env.IsDevelopment() || env.IsStaging();
              };
           
            // Exception will produce and returns from  FluentValidation RequestValidationBehavior
            x.Map<ValidationException>(ex => new ProblemDetailsWithCode
            {
                Title = "input validation rules broken",
                Status = (int)ex.StatusCode,
                Detail = ex.Message,
                Type = "https://somedomain/input-validation-rules-error", 
            });
          
        });
        return services;
    }

4. Startup
builder.Services.AddCustomProblemDetails();
app.UseProblemDetails();

validation error

@khellang
Copy link
Owner

I am develop this way but multiple error is not showing

I don't see you pulling out the Errors from the ValidationException and mapping it onto the ProblemDetailsWithCode class anywhere?

and output is unreadable exception

If you want to turn off the exception details, you just need to return false from your IncludeExceptionDetails hook.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants