Using Swashbuckle.AspNetCore v6.0.7 in an asp.net core project net5.0.
Let say I have models like these:
public enum MyEnum
{
A, B
}
and
public class MyModel
{
public MyEnum MyEnum { get; set; }
public MyEnum? MyEnum2 { get; set; }
}
and the swagger schema is generated like this:
"MyEnum": {
"enum": [
"A",
"B"
],
"type": "string"
},
"MyModel": {
"type": "object",
"properties": {
"myEnum": {
"$ref": "#/components/schemas/MyEnum"
},
"myEnum2": {
"$ref": "#/components/schemas/MyEnum"
}
},
"additionalProperties": false
}
As you can see, there is no difference between MyEnum and MyEnum? in the open-API JSON schema!
And seems nullable enum is not presented in the schema properly.
Does anyone have any idea how can I fix this?
Best
As Yiyi You suggested, I called UseAllOfToExtendReferenceSchemas in SwaggerGenOptions like this:
services.AddSwaggerGen(c =>
{
c.UseAllOfToExtendReferenceSchemas();
});
and now the schema is generated like:
"MyEnum": {
"enum": [
"A",
"B"
],
"type": "string"
},
"MyModel": {
"type": "object",
"properties": {
"myEnum": {
"allOf": [
{
"$ref": "#/components/schemas/MyEnum"
}
]
},
"myEnum2": {
"allOf": [
{
"$ref": "#/components/schemas/MyEnum"
}
],
"nullable": true
}
},
"additionalProperties": false
},
and there is "nullable": true for the type MyEnum?.
You can find more information here.
The following worked well for me:
_ = services.AddSwaggerGen(c =>
{
// Enables support for nullable object properties
c.UseAllOfToExtendReferenceSchemas();
// Enable detection of non nullable reference types to set Nullable flag accordingly on schema properties
c.SupportNonNullableReferenceTypes();
})
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