1

我们正在使用 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 循环中运行的规则

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 )。规则错误冒泡为

说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:FluentValidation.ValidationException:验证失败:

我期望的是流利的验证来处理错误并将其作为验证错误传递回 json 中的 ajax 请求

4

1 回答 1

3

我用 HandleErrorAttribute 捕获 ValidationException 并将 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());
    }
于 2016-04-05T15:39:31.830 回答