【发布时间】:2017-10-19 05:35:28
【问题描述】:
我目前正在使用 Mediatr 3 中的管道行为进行请求验证。如果发生任何故障,我遇到的所有示例都会抛出 ValidationException,而不是这样做,我想返回带有错误的响应。有人知道怎么做吗?
以下是验证管道的代码:
public class ValidationPipeline<TRequest, TResponse> :
IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>
{
private readonly IEnumerable<IValidator<TRequest>> _validators;
public ValidationPipeline(IEnumerable<IValidator<TRequest>> validators)
{
_validators = validators;
}
public Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next)
{
var failures = _validators
.Select(v => v.Validate(request))
.SelectMany(result => result.Errors)
.Where(f => f != null)
.ToList();
if (failures.Any())
{
throw new ValidationException(failures);
}
return next();
}
}
注意:我发现了这个问题Handling errors/exceptions in a mediator pipeline using CQRS?,我对答案中的第一个选项感兴趣,但没有关于如何做到这一点的明确示例。
这是我的响应类:
public class ResponseBase : ValidationResult
{
public ResponseBase() : base() { }
public ResponseBase(IEnumerable<ValidationFailure> failures) : base(failures) {
}
}
我在验证管道类中添加了以下签名:
public class ValidationPipeline<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>
where TResponse : ResponseBase
然后我在 Handle 方法中这样做了:
var response = new ResponseBase(failures);
return Task.FromResult<TResponse>(response);
但这给了我错误“无法转换为 TResponse”。
【问题讨论】:
-
return the response with the error-response是什么样的? -
管道
TResponse将与底层处理程序TResponse相同——ResponseBase : ValidationResult对我来说就像是代码味道。我不清楚您要达到的目标。 -
我正在尝试从 FluentValidation 的 ValidationResult 类继承
-
这意味着整个管道(包括您的主处理程序)将返回这种类型,对吗?
-
是的,完全正确。感谢您指出了这一点。所以我决定不从任何类继承 ResponseBase,它现在可以工作了!非常感谢。
标签: c# asp.net-mvc cqrs mediatr