Polymorphic derived types do not have discriminator property marked as required in OpenAPI schema.
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 281
Description
### Is there an existing issue for this?
- [x] I have searched the existing issues
### Describe the bug
```csharp
[JsonDerivedType(typeof(Bar), "bar")]
[JsonDerivedType(typeof(Baz), "baz")]
public abstract record Foo;
public record Bar(int Value) : Foo;
public record Baz(string Name) : Foo;
```
Generated schema
```yaml
"components": {
"schemas": {
"Foo": {
"required": [
"$type"
],
"type": "object",
"anyOf": [
{
"$ref": "#/components/schemas/FooBar"
},
{
"$ref": "#/components/schemas/FooBaz"
}
],
"discriminator": {
"propertyName": "$type",
"mapping": {
"bar": "#/components/schemas/FooBar",
"baz": "#/components/schemas/FooBaz"
}
}
},
"FooBar": {
"required": [
"value"
],
"properties": {
"$type": {
"enum": [
"bar"
],
"type": "string"
},
"value": {
"type": "integer",
"format": "int32"
}
}
},
"FooBaz": {
"required": [
"name"
],
"properties": {
"$type": {
"enum": [
"baz"
],
"type": "string"
},
"name": {
"type": "string"
}
}
}
}
}
```
In the schema, FooBar and FooBaz have required properties, but critically the discriminator property `$type` is not required,
even though it is required in the base class Foo. This is inconsistent and can cause issues when e.g.
trying to generate TypeScript classes from the Open API schema.
### Expected Behavior
Expected generated schema
```yaml
"components": {
"schemas": {
"Foo": {
"required": [
"$type"
],
"type": "object",
"anyOf": [
{
"$ref": "#/components/schemas/FooBar"
},
{
"$ref": "#/components/schemas/FooBaz"
}
],
"discriminator": {
"propertyName": "$type",
"mapping": {
"bar": "#/components/schemas/FooBar",
"baz": "#/components/schemas/FooBaz"
}
}
},
"FooBar": {
"required": [
"$type",
"value"
],
"properties": {
"$type": {
"enum": [
"bar"
],
"type": "string"
},
"value": {
"type": "integer",
"format": "int32"
}
}
},
"FooBaz": {
"required": [
"$type",
"name"
],
"properties": {
"$type": {
"enum": [
"baz"
],
"type": "string"
},
"name": {
"type": "string"
}
}
}
}
}
```
### Steps To Reproduce
An example reproducing this issue can be found at .
### Exceptions (if any)
_No response_
### .NET Version
9.0.2
### Anything else?
ASP.NET Core version: 9.0.2.
I do not believe this is the same as #57982
Contributor guide
Assessment
This issue has not been assessed yet.