Default value not working for enum's
See original GitHub issueDefault value is not working for enums, e.g.:
public ActionResult<PagedResults<string>> Get(
[FromQuery, BindRequired] string q,
[FromQuery]int page = 1,
[FromQuery]int pageSize = 20,
[FromQuery]AutocompleteMatchType matchType = AutocompleteMatchType.BeginFirst)
then in the generated JSON:
"parameters": [
{
"name": "q",
"in": "query",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "page",
"in": "query",
"schema": {
"type": "integer",
"format": "int32",
"default": 1
}
},
{
"name": "pageSize",
"in": "query",
"schema": {
"type": "integer",
"format": "int32",
"default": 20
}
},
{
"name": "matchType",
"in": "query",
"schema": {
"enum": [
"begin",
"any",
"beginFirst"
],
"type": "string"
}
}
]
Noting that there is no default value in the JSON for the enum, even though one exists.
This seems to be down to the fact that OpenApiPrimitiveFactory.FactoryMethodMap
does not contain any way to create an OpenApiPrimitive<T>
for an enum, therefore the call to schema.Default = OpenApiPrimitiveFactory.CreateFrom(parameterInfo.DefaultValue);
returns and sets a null
value within the method SwaggerGenerator.GenerateParameter(...)
making it look from then on as if there was no default value (even though parameterInfo.DefaultValue
with the correct default value does exist, and is passed in to that call).
I’d be interested to work on this if it’s considered useful. I’m not quite sure if it is even possible to generate an OpenApiPrimitive<T>
where T
is an enum type? If so, then some reflection-based code added in to OpenApiPrimitiveFactory.CreateFrom(...)
to deal with that sounds like it might be the way to go? (Noting that the default value for an enum depends on whether the values for the enum are being output as string
or int
, so it would be important to display the default value in the correct format as well.)
Issue Analytics
- State:
- Created 4 years ago
- Reactions:4
- Comments:18 (9 by maintainers)
@michaelakin My workaround is to use
UseInlineDefinitionsForEnums
If I use this method even if I have StringEnumConverter added to the Json serializer configuration, my API params now show just the numbers for the enum types instead of the names. The names have meaning to the API consumer, but the number values alone do not. I really need a default to be specified but with the enum being represented by its names not the number values.