Please consider the following method:
[HttpGet("abc")]
public List<BaseClass> GetThemAll()
There are 3 types that derive from BaseClass. I would like to provide documentation for the 3 available types.
Q: Is it possible to provide documentation for these 3 derived types (using NSwag)?
So far I've tried using <see
but the Models section of Swagger UI does not contain the subtypes.
/// <returns>(...) Returned types are: <see cref="TypeA"/>, <see cref="TypeB"/> or <see cref="TypeC"/></returns>
Its look like you can describe all derived types via KnownType
, like:
[KnownType(typeof(DerivedClass1))]
[KnownType(typeof(DerivedClass2))]
[KnownType(typeof(DerivedClass3))]
public class BaseClass { }
Also for visualize inheritance its possible to write own SchemaProcessor
. For example:
[KnownType(typeof(A))]
[KnownType(typeof(B))]
public class BaseType
{
public int Id { get; set; }
}
public class A : BaseType
{
public string Name { get; set; }
}
public class B : BaseType
{
public long A { get; set; }
}
[HttpGet("abc")]
public List<BaseType> GetThemAll()
public class InheritanceSchemaProcessor : ISchemaProcessor
{
public void Process(SchemaProcessorContext context)
{
if (context.Type.Name is nameof(BaseType))
{
var attributes = context.Type.GetCustomAttributes(typeof(KnownTypeAttribute), true) as Attribute[];
foreach (Attribute attribute in attributes)
{
var knownTypeAttribute = (KnownTypeAttribute) attribute;
var schema =
context.Generator.GenerateWithReference<JsonSchema>(knownTypeAttribute.Type.ToContextualType(), context.Resolver);
context.Schema.AnyOf.Add(schema);
}
context.Schema.Properties.Clear();
context.Schema.AllowAdditionalProperties = true;
}
}
}
and in Startup.cs
in ConfigureServices
:
services.AddOpenApiDocument(s =>
{
s.SchemaType = SchemaType.OpenApi3;
s.SchemaProcessors.Add(new InheritanceSchemaProcessor());
s.FlattenInheritanceHierarchy = true;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With