Hi @Geoff Olding ,
These additional class definitions appear in the Swagger UI (https://localhost:7103/swagger/index.html), but do not appear in swagger.json,
Below is a demo, you can refer to it.
PolymorphismDocumentFilter:
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Linq;
using System.Reflection;
namespace swagarcore5
{
public class PolymorphismDocumentFilter<T> : IDocumentFilter
{
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
RegisterSubClasses(context, typeof(T));
}
private static void RegisterSubClasses(DocumentFilterContext context, Type abstractType)
{
const string discriminatorName = "$type";
var schemaRepository = context.SchemaRepository.Schemas;
var schemaGenerator = context.SchemaGenerator;
if (!schemaRepository.TryGetValue(abstractType.Name, out OpenApiSchema parentSchema))
{
parentSchema = schemaGenerator.GenerateSchema(abstractType, context.SchemaRepository);
}
// set up a discriminator property (it must be required)
parentSchema.Discriminator = new OpenApiDiscriminator { PropertyName = discriminatorName };
parentSchema.Required.Add(discriminatorName);
if (!parentSchema.Properties.ContainsKey(discriminatorName))
parentSchema.Properties.Add(discriminatorName, new OpenApiSchema { Type = "string", Default = new OpenApiString(abstractType.FullName) });
// register all subclasses
var derivedTypes = abstractType.GetTypeInfo().Assembly.GetTypes()
.Where(x => abstractType != x && abstractType.IsAssignableFrom(x));
foreach (var type in derivedTypes)
schemaGenerator.GenerateSchema(type, context.SchemaRepository);
}
}
}
BaseClass:
public class BaseClass
{
public string Name { get; set; }
public string Description { get; set; }
}
register it in your Startup class
services.AddSwaggerGen(options =>
{
...
options.DocumentFilter<PolymorphismDocumentFilter<BaseClass>>();
...
});
result:
----------
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Qing Guo