Search code examples
c#.netenumsswaggerswashbuckle

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?


Solution

  • 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,
        }