I have an Asp.Net web API 5.2 project in c# and generating documentation with Swashbuckle.
I have model that contain inheritance something like having an Animal property from an Animal abstract class and Dog and Cat classes that derive from it.
Swashbuckle only shows the schema for the Animal class so I tried to play with ISchemaFilter (that what they suggest too) but I couldn't make it work and also I cannot find a proper example.
Anybody can help?
I'd like to follow up on Craig's answer.
If you use NSwag to generate TypeScript definitions from the Swagger API documentation generated with Swashbuckle (3.x at the time of writing) using the method explained in Paulo's answer and further enhanced in Craig's answer you will probably face the following problems:
Generated TypeScript definitions will have duplicate properties even though the generated classes will extend the base classes. Consider the following C# classes:
When using the aforementioned answers, the resulting TypeScript definition of
IBaseClass
andIChildClass
interfaces would look like this:As you can see, the
baseProperty
is incorrectly defined in both base and child classes. To solve this, we can modify theApply
method of thePolymorphismSchemaFilter<T>
class to include only owned properties to the schema, i.e. to exclude the inherited properties from the current types schema. Here is an example:Generated TypeScript definitions will not reference properties from any existing intermediate abstract classes. Consider the following C# classes:
In this case, the generated TypeScript definitions would look like this:
Notice how the generated
IChildClass
interface extendsISuperClass
directly, ignoring theIIntermediateClass
interface, effectively leaving any instance ofIChildClass
without theintermediateProperty
property.We can use the following code to solve this problem:
This will ensure that the child class correctly references the intermediate class.
In conclusion, the final code would then look like this:
To follow on from Paulo's great answer, if you're using Swagger 2.0, you'll need to modify the classes as shown:
It seems Swashbuckle doesn't implement polymorphism correctly and I understand the point of view of the author about subclasses as parameters (if an action expects an Animal class and behaves differently if you call it with a dog object or a cat object, then you should have 2 different actions...) but as return types I believe that it is correct to return Animal and the objects could be Dog or Cat types.
So to describe my API and produce a proper JSON schema in line with correct guidelines (be aware of the way I describe the disciminator, if you have your own discriminator you may need to change that part in particular), I use document and schema filters as follows:
What the previous code implements is specified here, in the section "Models with Polymorphism Support. It basically produces something like the following: