Stay Foolish
Stay Foolish

Reputation: 3756

Web API 2 documentation with Swagger and FluentValidation

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.

Upvotes: 3

Views: 3324

Answers (2)

Prayag Sagar
Prayag Sagar

Reputation: 671

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

Upvotes: 4

Benjamin Soulier
Benjamin Soulier

Reputation: 2263

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

Upvotes: -1

Related Questions