Oct 13, 2022

Exposing child class in Swagger documentation

Hello All,

Writing this post after a long time, will make sure to keep continue sharing my knowledge

Problem Statement: 

Need to expose inherited / child class into Swagger documentation

Use case:

This is very common issue, where you have multiple inheritance classes in your MVC application. And you need to expose all your child classes into Swagger documentation to make sure Solution/System Integrator should have visibility to use all possible cases based on their requirement.  


In WCF we have to decorate class by adding KnownType attribute to all your child class. In latest version of swagger new decoration has been added which is SwaggerSubTypes.

You have to decorate your all child class with SwaggerSubTypes attribute, this accepts array of types to expose all your child classes

Consider you have one base class Computer and two inherited classes Laptop and Desktop. You have exposed API to create new peripherals  


So base class have two properties, we will create two new base class to create inheritance 


Our goal is to expose all three object definition in Swagger, so for that lets add decoration to these classes


If you want to hide Computer then mark it as abstract. 

For this to get working in your code, you need to add few lines in Startup.cs file, copy below lines into ConfigureServices function

    services.AddSwaggerGen(c =>
        c.EnableAnnotations(enableSubTypeAnnotations: true);

You are done!