来自管道行为的 MediatR 流畅验证响应

INN*_*VTV 6 c# cqrs fluentvalidation mediatr asp.net-core

我有一个 MediatR 管道行为,用于使用 FluentValidation 库验证命令。我看过很多例子,你从行为中抛出 ValidationException,这对我来说很好用。但是在我的场景中,我想用验证错误更新我的响应对象。

我能够构建和运行以下代码。当我在 if 语句中设置断点时,CommandResponse 是按预期使用验证错误构造的 - 但是当原始调用者收到响应时,它为空:

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

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

    public Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
    {
        var context = new ValidationContext(request);

        // Run the associated validator against the request
        var failures = _validators
            .Select(v => v.Validate(context))
            .SelectMany(result => result.Errors)
            .Where(f => f != null)
            .ToList();

        if(failures.Count != 0)
        {
            var commandResponse = new CommandResponse(failures) { isSuccess = false };
            return commandResponse as Task<TResponse>;
        }
        else
        {   
            return next();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我认为这与我尝试将其转换为任务有关 - 但没有这个我会得到编译器错误。如果验证通过,我将返回与我的命令处理程序相同的类型,因此我不知道为什么它返回预期响应的空实例。我觉得有更好的方法来处理这个问题,但我尝试了许多变体都无济于事。有什么建议?有没有更好的模式可以使用?我更愿意将其保留在管道中,因为它将被大量重复使用。

INN*_*VTV 10

我最终向 MVC 项目添加了异常处理中间件。我没有尝试将验证错误作为对象传回,而是在管道行为内部抛出 ValidationException 并且中间件处理整个项目中的任何和所有异常。这实际上效果更好,因为我在处理链中更高的一个地方处理所有异常。

这是我发布的代码的更新部分:

if(failures.Count != 0)
{
    // If any failures are found, throw a custom ValidationException object
    throw new ValidationException(failures);
}
else
{   
    // If validation passed, allow the command or query to continue:
    return next();
}
Run Code Online (Sandbox Code Playgroud)

这是异常处理中间件:

public class ErrorHandlingMiddleware
{
    private readonly RequestDelegate next;

    public ErrorHandlingMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext context /* other dependencies */)
    {
        try
        {
            await next(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }


    private static Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        // Log issues and handle exception response

        if (exception.GetType() == typeof(ValidationException))
        {
            var code = HttpStatusCode.BadRequest;
            var result = JsonConvert.SerializeObject(((ValidationException)exception).Failures);
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = (int)code;
            return context.Response.WriteAsync(result);

        }
        else
        {
            var code = HttpStatusCode.InternalServerError;
            var result = JsonConvert.SerializeObject(new { isSuccess = false, error = exception.Message });
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = (int)code;
            return context.Response.WriteAsync(result);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在添加 MVC 之前在 Startup 中注册中间件:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMiddleware(typeof(ErrorHandlingMiddleware));
    app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)

注意:您还可以为中间件创建扩展方法:

public static class ErrorHandlingMiddlewareExtension
{
    public static IApplicationBuilder UseErrorHandlingMiddleware(
        this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<ErrorHandlingMiddleware>();
    }
}
Run Code Online (Sandbox Code Playgroud)

这允许您像这样注册它:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseErrorHandlingMiddleware();
    app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)