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

时间:2015-10-22 10:27:10

标签: c# asp.net-web-api async-await fluentvalidation model-validation

我设置了一个web api项目,使用FluentValidation webapi integration package进行FluentValidation。然后我创建了一个使用CustomAsync(...)对数据库运行查询的验证器。

问题是在等待数据库任务时验证似乎已死锁。我做了一些调查,似乎MVC ModelState API是同步的,它调用了一个同步Validate(...)方法,使FluentValidation调用task.Result,导致死锁。

假设异步调用不能与webapi集成验证一起使用是否正确?

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

1 个答案:

答案 0 :(得分: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";
            }
        }
    }
}
相关问题