3

We are developing web api using web api 2 and fluent validation. Everything is working fine.

However, we realize the rules we define in fluent validation is not getting respect by the swagger (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. I know we can make that work by using .net annotation attribute. But we don't want to separate the validation logic (some of the logic are not easy to do in .net annotation.

Any comment on that will be appreciated.

Prayag Sagar
  • 651
  • 1
  • 8
  • 21
Stay Foolish
  • 3,636
  • 3
  • 26
  • 30

2 Answers2

4

You can include your Fluent Validation rules to Swagger documentation by adding a custom SchemaFilter to your Swagger configuration.

Add the below code to the SwaggerConfig.cs file:

c.SchemaFilter<FluentValidationRules>();

And inherit ISchemaFilter using the code below:

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);
                }
            }
        }
    }
}
Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84
Prayag Sagar
  • 651
  • 1
  • 8
  • 21
  • what about custom validators? I have a custom validator and want to get it inside of the loop as a CustomValidator. What is type for this customValidator? Please think about writing one SchemaFilter for all fluent validation class. – cimey Jun 18 '19 at 11:52
-1

Looking at information from SwashBluckle on Github, it doesn't seem that you can use Fluent Validation with it.

Benjamin Soulier
  • 2,223
  • 1
  • 18
  • 30