How to show Enums as Strings in Swashbuckle.AspNetCore

Andrew Varnon
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>();
});

--

--

Andrew Varnon
Andrew Varnon

Written by Andrew Varnon

I am a full stack developer and architect, specializing in .Net and Azure.

Responses (3)