简体   繁体   English

带有Swagger和FluentValidation的Web API 2文档

[英]Web API 2 documentation with Swagger and FluentValidation

We are developing web api using web api 2 and fluent validation. 我们正在使用Web API 2和流畅的验证功能来开发Web API。 Everything is working fine. 一切正常。

However, we realize the rules we define in fluent validation is not getting respect by the swagger (Swashbuckle). 但是,我们意识到我们在流利验证中定义的规则并没有得到大张旗鼓(Swashbuckle)的尊重。

For example 例如

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

If I define the name as required field in the fluent validator, the property is marked as optional in the api. 如果我在流利的验证器中将名称定义为必填字段,则该属性在api中被标记为可选。 I know we can make that work by using .net annotation attribute. 我知道我们可以通过使用.net批注属性来实现该功能。 But we don't want to separate the validation logic (some of the logic are not easy to do in .net annotation. 但是我们不想分离验证逻辑(某些逻辑在.net批注中不容易实现。

Any comment on that will be appreciated. 任何意见,将不胜感激。

You can include your Fluent Validation rules to Swagger documentation by adding a custom SchemaFilter to your Swagger configuration. 通过将自定义SchemaFilter添加到Swagger配置中,可以将Fluent Validation规则包括到Swagger文档中。

Add the below code to the SwaggerConfig.cs file: 将以下代码添加到SwaggerConfig.cs文件:

c.SchemaFilter<FluentValidationRules>();

And inherit ISchemaFilter using the code below: 并使用以下代码继承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);
                }
            }
        }
    }
}

查看来自 Github上SwashBluckle的信息 ,似乎您不能对其使用Fluent Validation。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM