MVC 中 Fluent Validation 的 ValidationException

Fluent Validation’s ValidationException inside MVC

我们使用的是 CQRS 模式,我们在流畅验证的错误处理方面遇到了问题。 (CQRS 模式@https://lostechies.com/jimmybogard/2015/05/05/cqrs-with-mediatr-and-automapper/

public class OtherSpecified : AbstractValidator<Command>
{
    public OtherSpecified(ApplicationDbContext context)
    {
        RuleFor(x => x.Other).NotNull();
    }
}

public class DepartmentSpecified : AbstractValidator<Command>
{
    public DepartmentSpecified(ApplicationDbContext context)
    {
        RuleFor(x => x.Department).NotNull();
    }
}

现在我们注入我们的验证处理程序,这样我们就可以 运行 基于来自 http://lostechies.com/jimmybogard/2014/09/09/tackling-cross-cutting-concerns-with-a-mediator-pipeline/ 的信息的多个抽象验证器。这行得通,但是因为我可以在 foreach 循环

中看到规则 运行ning
public TResponse Handle(TRequest request)
{
    var context = new ValidationContext(request);
    var result = new ValidationResult();

    var list = _validators.ToList();
    foreach (var validator in list)
    {
        var results = validator.Validate(request);
        foreach (var validationFailure in results.Errors)
        {
            result.Errors.Add(validationFailure);   
            //temp testing code below
            if (results.Errors.Count > 0)
                throw new ValidationException(result.Errors);

        }
    }

    if (result.Errors != null &&
        result.Errors.Count > 0)
    {
        throw new ValidationException(result.Errors);
    } 
    return _inner.Handle(request);
}

问题是流式验证异常 (ValidationException) 没有得到处理。规则错误冒出

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: FluentValidation.ValidationException: Validation failed:

我希望 Fluent 验证能够处理错误并将其作为验证错误传回 json 中的 ajax 请求

我用 HandleError 属性捕获了 ValidationException 并且 return json 到 ajax 请求。

public class ValidationExceptionHandlerErrorAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            //only handle ValidationExceptions
            if ((filterContext.Exception as ValidationException) != null)
            {
                var result = new ContentResult();
                //Add errors to Model State so they are handled auto-magically
                foreach (var validationsfailures in (filterContext.Exception as ValidationException).Errors)
                {
                    filterContext.Controller.ViewData.ModelState.AddModelError(validationsfailures.PropertyName,validationsfailures.ErrorMessage);
                }
                //convert to json and return to ajax request
                string content = JsonConvert.SerializeObject(filterContext.Controller.ViewData.ModelState,
                    new JsonSerializerSettings
                    {
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                    });
                result.Content = content;
                result.ContentType = "application/json";
                filterContext.HttpContext.Response.StatusCode = 400;
                filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
                filterContext.Result = result;
                filterContext.ExceptionHandled = true;
            }
        }
    }

然后我在这里接线

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        ..
        ..
        filters.Add(new ValidationExceptionHandlerErrorAttribute());
    }