micro-elements/MicroElements.Swashbuckle.FluentValidation

FluentValidation rules not emited on inherited property in one class, but does in another

icnocop opened this issue · 5 comments

Hi.

I'm experiencing an issue where the FluentValidation rules are not emitted in swagger.json for an inherited property in one class, but those rules are emitted in another class.

I created an example in my fork here:
https://github.com/icnocop/MicroElements.Swashbuckle.FluentValidation

Steps to reproduce:

  1. Build and run the SampleWebApi project
  2. Expand Issue100 > "POST /api/Issue100/AddMyEntity100" > Parameters > Request Body > Schema > MyEntity100 > person
  3. Expand Person100A
  4. Expand Person100B
  5. Notice the age property has the expected FluentValidation rules in Person100B, but not in Person100A.

Any ideas?

Thank you!

Current state:
изображение

Looking for validator for Person100A: (validator not found)
изображение

GetValidator looks for registered validator for type Person100A and it fails because no real validator registered in factory.
In future we can support PolymorficValidator but now we have workaround:

Solution:

  1. Create real class:
    изображение

  2. Move validator from abstract BasePerson100 to MyEntity100 (according FV docs) (OPTIONAL)

        [SwaggerDiscriminator("discriminator")]
        [SwaggerSubType(typeof(Person100A), DiscriminatorValue = Person100A.DiscriminatorValue)]
        [SwaggerSubType(typeof(Person100B), DiscriminatorValue = Person100B.DiscriminatorValue)]
        [JsonConverter(typeof(JsonInheritanceConverter), "discriminator")]
        [JsonInheritance(Person100A.DiscriminatorValue, typeof(Person100A))]
        [JsonInheritance(Person100B.DiscriminatorValue, typeof(Person100B))]
        public abstract class BasePerson100
        {
        }

        public class MyEntity100
        {
            public BasePerson100 Person { get; set; }

            [UsedImplicitly]
            public class MyEntity100Validator : AbstractValidator<MyEntity100>
            {
                public MyEntity100Validator()
                {
                    this.RuleFor(x => x.Person)
                        .SetInheritanceValidator(x =>
                        {
                            x.Add<Person100A>(new Person100A.Person100AValidator());
                            x.Add<Person100B>(new Person100B.Person100BValidator());
                        });
                }
            }
        }

There is some mismatch between dynamic FluentValidation nature and OpenApi static document generation

Thank you!

After updating the code as suggested, the FV rules are emitted on Person100A as expected.

Thank you again for your help. 🙏

Thank you Rami!