How to show Enums as Strings in Swashbuckle.AspNetCore
Apr 22, 2021
Once upon a time you could use DescribeAllEnumsAsStrings() to display enums as string instead of numbers in Swagger/Swashbuckle. Unfortunately, that method is now obsolete. We can still achieve the same effect with a little more work. First, define a Schema Filter class to handle the conversion.
public class EnumSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema model, SchemaFilterContext context)
{
if (context.Type.IsEnum)
{
model.Enum.Clear();foreach (string enumName in Enum.GetNames(context.Type))
{
System.Reflection.MemberInfo memberInfo = context.Type.GetMember(enumName).FirstOrDefault(m => m.DeclaringType == context.Type);
EnumMemberAttribute enumMemberAttribute = memberInfo == null
? null
: memberInfo.GetCustomAttributes(typeof(EnumMemberAttribute), false).OfType<EnumMemberAttribute>().FirstOrDefault();
string label = enumMemberAttribute == null || string.IsNullOrWhiteSpace(enumMemberAttribute.Value)
? enumName
: enumMemberAttribute.Value;model.Enum.Add(new OpenApiString(label));
}
}
}
}
Next, register the class with Swashbuckle/Swagger
services.AddSwaggerGen(c =>
{
c.SchemaFilter<EnumSchemaFilter>();
});