Generating OpenApi (Swagger) with Swashbuckle in GeneratePolymorphicSchemas mode, how to configure it to use $type prop from JSON.NET?

Viewed 784

I have an ASP.NET Core 3 WebApi with polymorphic DTOs. I'm using Json.NET to add $type field to my json, i.e. "$type":"CrazyIvanMotors.DTO.Animal.Dog, CrazyIvanMotors.DTO". I'm trying to generate an OpenApi 3.0.1 schema.

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers()
            .AddNewtonsoftJson((config) => 
            {
                config.SerializerSettings.TypeNameHandling = TypeNameHandling.Objects;
            });


    // Register the Swagger generator, defining 1 or more Swagger documents
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
        c.GeneratePolymorphicSchemas();
    });
}

Swashbuckle properly detects polymorphic classes and adds $type property, but does not put correct constant values into type or generate any mapping as described here OpenApi doc inheritance and polymorphism

      "Animal": {
        "required": [
          "$type"
        ],
        "type": "object",
        "properties": {
          "$type": {
            "type": "string"
          },
          "name": {
            "type": "string",
            "nullable": true
          }
        },
        "additionalProperties": false,
        "discriminator": {
          "propertyName": "$type"
        }
      },
      "Dog": {
        "allOf": [
          {
            "$ref": "#/components/schemas/Animal"
          },
          {
            "type": "object",
            "properties": {
              "sizeCategory": {
                "type": "string",
                "nullable": true
              }
            },
            "additionalProperties": false
          }
        ]
      }

Am I missing some configuration here?

0 Answers
Related