dotnet / dotnet/aspnetcore

OpenApi polymorphic types missing discriminators

Open
#57,982 20 comments 17 reactions 1 assignee Claimed by @snemeckayova View on GitHub
area-minimal area-mvc feature-openapi
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 5h
Merged PRs (30d)
276

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

I have some polymorphic types

```cs
[JsonPolymorphic(TypeDiscriminatorPropertyName = "$dis")]
[JsonDerivedType(typeof(Cat), typeDiscriminator: "cat")]
[JsonDerivedType(typeof(Dog), typeDiscriminator: "dog")]
public class Pet
{
public string Name { get; set; } = default!;
}
public class Dog : Pet
{
public string? Breed { get; set; }
}

public class Cat : Pet
{
public int? Lives { get; set; }
}
```

This result in
```json
"Pet": {
"type": "object",
"anyOf": [
{
"$ref": "#/components/schemas/PetCat"
},
{
"$ref": "#/components/schemas/PetDog"
},
{
"$ref": "#/components/schemas/PetBase"
}
]
},
"PetBase": {
"properties": {
"name": {
"type": "string"
}
}
},
"PetDog": {
"required": [
"$dis"
],
"properties": {
"$dis": {
"enum": [
"dog"
],
"type": "string"
},
"breed": {
"type": "string",
"nullable": true
},
"name": {
"type": "string"
}
}
},
```

This is the equivalent generated by Swashbuckle
```json
"Pet": {
"required": [
"$dis"
],
"type": "object",
"properties": {
"$dis": {
"type": "string"
},
"name": {
"type": "string",
"nullable": true
}
},
"additionalProperties": false,
"discriminator": {
"propertyName": "$dis",
"mapping": {
"dog": "#/components/schemas/Dog",
"cat": "#/components/schemas/Cat"
}
}
},
"Dog": {
"allOf": [
{
"$ref": "#/components/schemas/Pet"
},
{
"type": "object",
"properties": {
"breed": {
"type": "string",
"nullable": true
}
},
"additionalProperties": false
}
]
},
```

### Expected Behavior

The type Dog is renamed to PetDog; not expected.

Pet has the name property defined in code, but this shows up on PetBase and PetDoc in schema. I can't see how you can write code that operates on the Pet type and use the Name property.

Swashbuckle adds a discriminator section that is completely missing. OpenApi seems to be quite flexible in some areas; is this just another way of representing things. Code generator will have to handle both?

### Steps To Reproduce

https://github.com/dnv-kimbell/openapi-inlineschema

### Exceptions (if any)

_No response_

### .NET Version

9.0 RC1

### Anything else?

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.