Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude specific Enum values from Swagger

I always add an Uninitialized value to all my enums and set it to 0 to handle cases where I deserialize an object that has an enum property value that was never set.

enum MyEnum
{
    Uninitialized = 0,
    MyEnumValue1 = 1,
    MyEnumValue2 = 2,
    MyEnumValue3 = 3,
}

However, I don't want the Uninitialized value to show up in my Swagger documentation.

I've tried adding the [JsonIgnore] attribute to that value, but that didn't work.

Anyone know how to accomplish this?

like image 525
ErikMuir Avatar asked Aug 25 '26 06:08

ErikMuir


2 Answers

Just in case anyone else struggles with this. You can create a custom SchemaFilter and populate the Enum property filtering on those enum values with a custom attribute (in this example: OpenApiIgnoreEnumAttribute).

    public class OpenApiIgnoreEnumSchemaFilter : ISchemaFilter
    {
        public void Apply(OpenApiSchema schema, SchemaFilterContext context)
        {
            if (context.Type.IsEnum)
            {
                var enumOpenApiStrings = new List<IOpenApiAny>();

                foreach (var enumValue in Enum.GetValues(context.Type))
                {
                    var member = context.Type.GetMember(enumValue.ToString())[0];
                    if (!member.GetCustomAttributes<OpenApiIgnoreEnumAttribute>().Any())
                    {
                        enumOpenApiStrings.Add(new OpenApiString(enumValue.ToString()));
                    }
                }

                schema.Enum = enumOpenApiStrings;
            }
        }
    }
    public class OpenApiIgnoreEnumAttribute : Attribute
    {
    }
    public enum ApplicationRole
    {
        [OpenApiIgnoreEnum]        
        DoNotExpose = 1,        
        ValueA = 2,        
        ValueB = 3,
    }
like image 198
Royston46 Avatar answered Aug 26 '26 21:08

Royston46


You can simply omit your Uninitialized enum value to solve this.

Enums can actually contain values other than the ones you explicitly define. I can do var myEnumValue = (MyEnum)12345; and it won't break or throw an exception, but it won't match any of the explicitly defined enum values either.

As long as the defined values do not equal default(int), or the default of whatever you chose your enum type to be, you can still work with the enum as expected, and catch unitialized values with a switch default case.

This has the added benefit of catching all unlisted enum values, not just the one you explicitly declared.

like image 43
Flater Avatar answered Aug 26 '26 19:08

Flater



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!