gpt4 book ai didi

c# - 返回包含 MediatR 管道行为错误的响应

转载 作者:行者123 更新时间:2023-12-05 05:59:38 27 4
gpt4 key购买 nike

我是 MediatR 的新手,尝试使用管道行为进行请求验证,如果发生任何错误,我遇到的所有示例都会抛出 ValidationException。
下面的代码是验证管道的示例:

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

public ValidationPipeline(IEnumerable<IValidator<TRequest>> validators)
{
_validators = validators;
}

public Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
var context = new ValidationContext<TRequest>(request);
var validationFailures = _validators
.Select(validator => validator.Validate(context))
.SelectMany(validationResult => validationResult.Errors)
.Where(validationFailure => validationFailure != null)
.ToList();

if (validationFailures.Any())
{
throw new FluentValidation.ValidationException(validationFailures);
}

return next();
}
}

这个方法工作正常,但我想返回带有验证错误的响应(没有)抛出异常,所以我尝试了这个:

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

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

public Task<BaseResponse<TResponse>> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<BaseResponse<TResponse>> next)
{
var context = new ValidationContext<TRequest>(request);
var validationFailures = _validators
.Select(validator => validator.Validate(context))
.SelectMany(validationResult => validationResult.Errors)
.Where(validationFailure => validationFailure != null)
.ToList();

if (validationFailures.Any())
{
return Task.FromResult(new BaseResponse<TResponse>
{
Code = 400,
Message = "Validation error",
Error = validationFailures.Select(err => err.ErrorMessage)
});
}
else
{
return next();
}
}

但是现在验证管道代码没有执行,
并执行到常规处理程序(例如:注册用户处理程序)。

我的回应(在所有处理程序中使用):

public class BaseResponse<TResponse>
{
public int Code { get; set; }
public string Message { get; set; }
public TResponse Result { get; set; }
public object Error { get; set; }
public string TraceIdentifier { get; set; }
}

像这样用 DI 注册行为:

services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));

我们将不胜感激。

最佳答案

我使用了下一个方法。首先我使用 Adrdalis.Result或通过 nuget Ardalist.Result我发现它非常有用。流水线代码:

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

public FluentValidationPipelineBehaviour(IEnumerable<IValidator<TRequest>> validators)
{
_validators = validators;
}
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
var requestType = request.GetType();
if (requestType != null)
{
var attribute = requestType.GetCustomAttribute<FluentValidationAttribute>();
if (attribute != null && attribute.IsEnabled)
{
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())
{
if (attribute.ThrowExceptionOnError)
{
throw new ValidationException(failures);
}
return GetValidatableResult(failures.AsErrors());
}
}
}
return await next();
}

private static TResponse GetValidatableResult(List<ValidationError> validationErrors)
{
#pragma warning disable CS8603
#pragma warning disable CS8602
#pragma warning disable CS8600
return (TResponse)(typeof(Result<>).MakeGenericType(typeof(TResponse).GetGenericArguments())
.GetMethod("Invalid").Invoke(null, new object?[] { validationErrors }));
#pragma warning restore CS8600
#pragma warning restore CS8602
#pragma warning restore CS8603
}
}

我正在使用 FluentValidationAttribute 来配置 fluentvalidation 行为

[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public class FluentValidationAttribute : Attribute
{
public bool IsEnabled { get; set; } = true;
public bool ThrowExceptionOnError { get; set; } = false;
}

在命令/查询等上使用它;

关于c# - 返回包含 MediatR 管道行为错误的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68072671/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com