Last active
February 4, 2019 12:30
-
-
Save edfarrow/3162b0b7f7940e92b4d38da9b741fa4c to your computer and use it in GitHub Desktop.
Display enums with string description in Swashbuckle/Swagger (ASP.NET Core 2)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Add enum value descriptions to Swagger | |
/// </summary> | |
public class EnumDocumentFilter : IDocumentFilter | |
{ | |
/// <inheritdoc /> | |
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context) | |
{ | |
foreach (var schemaDictionaryItem in swaggerDoc.Definitions) | |
{ | |
var schema = schemaDictionaryItem.Value; | |
foreach (var propertyDictionaryItem in schema.Properties) | |
{ | |
var property = propertyDictionaryItem.Value; | |
var propertyEnums = property.Enum; | |
if (propertyEnums != null && propertyEnums.Count > 0) | |
{ | |
property.Description += DescribeEnum(propertyEnums); | |
} | |
} | |
} | |
if (swaggerDoc.Paths.Count <= 0) return; | |
// add enum descriptions to input parameters | |
foreach (var pathItem in swaggerDoc.Paths.Values) | |
{ | |
DescribeEnumParameters(pathItem.Parameters); | |
// head, patch, options, delete left out | |
var possibleParameterisedOperations = new List<Operation> { pathItem.Get, pathItem.Post, pathItem.Put }; | |
possibleParameterisedOperations.FindAll(x => x != null) | |
.ForEach(x => DescribeEnumParameters(x.Parameters)); | |
} | |
} | |
private static void DescribeEnumParameters(IList<IParameter> parameters) | |
{ | |
if (parameters == null) return; | |
foreach (var param in parameters) | |
{ | |
if (param is NonBodyParameter nbParam && nbParam.Enum?.Any() == true) | |
{ | |
param.Description += DescribeEnum(nbParam.Enum); | |
} | |
} | |
} | |
private static string DescribeEnum(IEnumerable<object> enums) | |
{ | |
var enumDescriptions = new List<string>(); | |
Type type = null; | |
foreach (var enumOption in enums) | |
{ | |
if (type == null) | |
{ | |
type = enumOption.GetType(); | |
} | |
var name = Enum.GetName(type, enumOption); | |
if (!string.IsNullOrWhiteSpace(name)) | |
{ | |
var description = new StringBuilder(name); | |
// process description | |
for (var i = description.Length - 1; i > 0; i--) | |
{ | |
if (i > 0 && char.IsUpper(description[i])) | |
{ | |
description.Insert(i, ' '); | |
} | |
} | |
enumDescriptions.Add($"{Convert.ChangeType(enumOption, type.GetEnumUnderlyingType())} = {description.ToString()}"); | |
} | |
} | |
return $"{Environment.NewLine}{string.Join(Environment.NewLine, enumDescriptions)}"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment