ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-06-23 14:53:59  阅读:206  来源: 互联网

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


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

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

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

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

解决方法:

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

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";
            }
        }
    }
}

标签:c,asp-net-web-api,async-await,fluentvalidation,model-validation
来源: https://codeday.me/bug/20190623/1271848.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有