【问题标题】:Web API 2 documentation with Swagger and FluentValidation带有 Swagger 和 FluentValidation 的 Web API 2 文档
【发布时间】:2016-08-16 04:25:37
【问题描述】:

我们正在使用 web api 2 和流利的验证来开发 web api。一切正常。

但是,我们意识到我们在 fluent 验证中定义的规则并没有得到大张旗鼓的尊重 (Swashbuckle)。

例如

Class Customer {
    public string Name {get;set;}
}

如果我在 fluent 验证器中将名称定义为必填字段,则该属性在 api 中被标记为可选。我知道我们可以通过使用 .net 注释属性来完成这项工作。但是我们不想分离验证逻辑(有些逻辑在.net注解中不容易做到。

对此的任何评论将不胜感激。

【问题讨论】:

标签: c# asp.net-web-api asp.net-web-api2 swagger fluentvalidation


【解决方案1】:

您可以通过在 Swagger 配置中添加自定义 SchemaFilter 来将 Fluent Validation 规则包含到 Swagger 文档中。

将以下代码添加到SwaggerConfig.cs 文件中:

c.SchemaFilter<FluentValidationRules>();

并使用下面的代码继承ISchemaFilter

public class FluentValidationRules : ISchemaFilter
{
    public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
    {
        var validator = new Customer(); //Your fluent validator class

        schema.required = new List<string>();

        var validatorDescriptor = validator.CreateDescriptor();

        foreach (var key in schema.properties.Keys)
        {
            foreach (var validatorType in validatorDescriptor.GetValidatorsForMember(key))
            {
                if (validatorType is NotEmptyValidator)
                {
                    schema.required.Add(key);
                }
            }
        }
    }
}

【讨论】:

  • 自定义验证器呢?我有一个自定义验证器,并希望将其作为 CustomValidator 放入循环中。这个 customValidator 的类型是什么?请考虑为所有流畅的验证类编写一个 SchemaFilter。
【解决方案2】:

看Github上的information from SwashBluckle,好像不能用Fluent Validation。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-05
    • 2016-02-14
    • 2017-04-01
    • 1970-01-01
    • 2016-01-03
    • 2016-03-22
    • 2017-03-08
    • 1970-01-01
    相关资源
    最近更新 更多