Skip to content

SwaggerGen - Improved handling of dictionaries with enum key #3068

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -350,16 +350,18 @@ private OpenApiSchema CreateArraySchema(DataContract dataContract, SchemaReposit

private OpenApiSchema CreateDictionarySchema(DataContract dataContract, SchemaRepository schemaRepository)
{
if (dataContract.DictionaryKeys != null)
var knownKeysProperties = dataContract.DictionaryKeys?.ToDictionary(
name => name,
_ => GenerateSchema(dataContract.DictionaryValueType, schemaRepository));

if (knownKeysProperties?.Count > 0)
{
// This is a special case where the set of key values is known (e.g. if the key type is an enum)
return new OpenApiSchema
{
Type = "object",
Properties = dataContract.DictionaryKeys.ToDictionary(
name => name,
name => GenerateSchema(dataContract.DictionaryValueType, schemaRepository)),
AdditionalPropertiesAllowed = false,
Properties = knownKeysProperties,
AdditionalPropertiesAllowed = false
};
}
else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ public void GenerateSchema_DedupsEnumValues_IfEnumTypeHasDuplicateValues()

[Theory]
[InlineData(typeof(IDictionary<string, int>), "integer")]
[InlineData(typeof(IDictionary<EmptyIntEnum, int>), "integer")]
[InlineData(typeof(IReadOnlyDictionary<string, bool>), "boolean")]
[InlineData(typeof(IDictionary), null)]
[InlineData(typeof(ExpandoObject), null)]
Expand Down
6 changes: 5 additions & 1 deletion test/Swashbuckle.AspNetCore.TestSupport/Fixtures/Enums.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ public enum ShortEnum:short
Value8 = 8,
}

public enum EmptyIntEnum:int
{
}

public enum IntEnum:int
{
Value2 = 2,
Expand All @@ -27,4 +31,4 @@ public enum LongEnum:long
Value4 = 4,
Value8 = 8,
}
}
}