如何在Web API中使用FluentValidation执行异步ModelState验证?

Nat*_*tan 4 c# model-validation fluentvalidation async-await asp.net-web-api

我通过使用针对FluentValidation的webapi集成包,设置了一个Web api项目以使用FluentValidation。然后,我创建了一个验证器,该验证器CustomAsync(...)用于对数据库运行查询。

问题在于,等待数据库任务时验证似乎陷入僵局。我进行了一些调查,看来MVC ModelState API是同步的,并且它调用Validate(...)使FluentValidation 调用的同步方法task.Result,从而导致死锁。

假设异步调用无法与Webapi集成验证一起使用是否正确?

如果是这样,还有什么选择?WebApi ActionFilters似乎支持异步处理。我是否需要构建自己的过滤器来手动处理验证,或者是否已经存在我没有看到的东西?

Nat*_*tan 6

我最终创建了一个自定义过滤器,并完全跳过了内置验证:

public class WebApiValidationAttribute : ActionFilterAttribute
{
    public WebApiValidationAttribute(IValidatorFactory factory)
    {
        _factory = factory;
    }

    IValidatorFactory _factory;

    public override async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
    {
        if (actionContext.ActionArguments.Count > 0)
        {
            var allErrors = new Dictionary<string, object>();

            foreach (var arg in actionContext.ActionArguments)
            {
                // skip null values
                if (arg.Value == null)
                    continue;

                var validator = _factory.GetValidator(arg.Value.GetType());

                // skip objects with no validators
                if (validator == null)
                    continue;

                // validate
                var result = await validator.ValidateAsync(arg.Value);

                // if there are errors, copy to the response dictonary
                if (!result.IsValid)
                {
                    var dict = new Dictionary<string, string>();

                    foreach (var e in result.Errors)
                        dict[e.PropertyName] = e.ErrorMessage;

                    allErrors.Add(arg.Key, dict);
                }
            }

            // if any errors were found, set the response
            if (allErrors.Count > 0)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, allErrors);
                actionContext.Response.ReasonPhrase = "Validation Error";
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)