jbogard / MediatR

Simple, unambitious mediator implementation in .NET
Apache License 2.0
10.91k stars 1.16k forks source link

ipipline handle are not work #950

Closed alihmaidi1 closed 11 months ago

alihmaidi1 commented 11 months ago

Hello i am using mediatr 12.1.1 and i try to build validation by ipipline behavior but its not work for me this is me code

using FluentValidation;
using MediatR;
using Microsoft.AspNetCore.Mvc;

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

    public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators) => _validators = validators;

    public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
    {

        if (_validators.Any())
        {
            var context = new ValidationContext<TRequest>(request);
            var validationResults = await Task.WhenAll(_validators.Select(v => v.ValidateAsync(context, cancellationToken)));
            var failures = validationResults.SelectMany(r => r.Errors).Where(f => f != null).ToList();
            if (failures.Count != 0)
                throw new ValidationException("Validation Error", failures);
        }
        return await next();

    }
}

using FluentValidation;
using MediatR;
using Microsoft.Extensions.DependencyInjection;

using System.Reflection;

namespace ecommerce.user
{
    public static class DependencyInjection
    {
        public static IServiceCollection AddUserdependency(this IServiceCollection services)
        {
            services.AddMediatR(config =>config.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));
            services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());
            services.AddTransient(typeof(IPipelineBehavior<,>),typeof(ValidationBehavior<,>));           
            services.AddAutoMapper(Assembly.GetExecutingAssembly());

            return services;
        }

    }
}

using ecommerce_shared.Exceptions;
using ecommerce_shared.OperationResult.Base;
using FluentValidation;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace ecommerce_shared.Middleware
{
    public class ErrorHandling : IMiddleware
    {
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            try
            {

                await next(context);
            }
            catch (Exception error)
            {

                var response=context.Response;
                response.ContentType= "application/json";
                var Result = new OperationResultBase<string>() { };

                switch (error)
                {

                    case ValidationException exception:
                        Result.Message = exception.Message;
                        Result.StatusCode = (int)HttpStatusCode.UnprocessableEntity;
                        response.StatusCode = (int)HttpStatusCode.UnprocessableEntity;
                        Result.Errors = exception.Errors.Select(f => f.PropertyName + ":" + f.ErrorMessage).ToList(); ;
                        break;

                    case UnAuthenticationException exception:
                        Result.Message = exception.Message;
                        Result.StatusCode = (int)HttpStatusCode.Unauthorized;
                        response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        break;

                    case UnAuthorizationException exception:
                        Result.Message = exception.Message;
                        Result.StatusCode = (int)HttpStatusCode.Forbidden;
                        response.StatusCode = (int)HttpStatusCode.Forbidden;
                        break;

                    case Exception exception:
                        Result.Message = exception.Message;
                        Result.StatusCode= (int)HttpStatusCode.InternalServerError;
                        response.StatusCode= (int)HttpStatusCode.InternalServerError;
                        break;

                }

                var errors= JsonSerializer.Serialize(Result);
                await response.WriteAsync(errors);

            }
        }
    }
}

and this is my reponse always

{
  "Result": null,
  "Message": "Validation failed: \r\n -- Email: 'Email' is not a valid email address. Severity: Error\r\n -- Email: 'Email' is not a valid email address. Severity: Error",
  "StatusCode": 422,
  "Errors": [
    "Email:'Email' is not a valid email address.",
    "Email:'Email' is not a valid email address.",
    "Email:'Email' is not a valid email address."
  ]
}
alihmaidi1 commented 11 months ago

@jbogard please can you help me : )