Swagger UI Web Api documentation Present enums as strings?

后端 未结 20 2043
半阙折子戏
半阙折子戏 2020-11-27 11:31

Is there a way to display all enums as their string value in swagger instead of their int value?

I want to be able to submit POST actions and put enums according to

20条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 11:32

    There were a number of shortcomings I found in the other answers for what we were looking for, so I thought I'd supply my own take on this. We're using ASP.NET Core 3.1 with System.Text.Json, but our approach works irrespective of the JSON serializer used.

    Our goal was to accept lower-camel-cased enum string values in both the ASP.NET Core API as well as document the same in Swagger. We're currently making use of [DataContract] and [EnumMember], so the approach is to take the lower-camel-cased value from the EnumMember value property and use that across the board.

    Our sample enum:

    [DataContract]
    public class enum Colors
    {
      [EnumMember(Value="brightPink")]
      BrightPink,
      [EnumMember(Value="blue")]
      Blue
    }
    

    We'll use the EnumMember values in Swashbuckle by using an ISchemaFilter as in the following:

    public class DescribeEnumMemberValues : ISchemaFilter
    {
        public void Apply(OpenApiSchema schema, SchemaFilterContext context)
        {
            if (context.Type.IsEnum)
            {
                schema.Enum.Clear();
    
                //Retrieve each of the values decorated with an EnumMember attribute
                foreach (var member in context.Type.GetMembers())
                {
                    var memberAttr = member.GetCustomAttributes(typeof(EnumMemberAttribute), false).FirstOrDefault();
                    if (memberAttr != null)
                    {
                        var attr = (EnumMemberAttribute) memberAttr;
                        schema.Enum.Add(new OpenApiString(attr.Value));
                    }
                }
            }
        }
    }
    

    We're using a third-party NuGet package (GitHub repo) to ensure that this naming scheme is also utilized in ASP.NET Core. Configure it in Startup.cs within ConfigureServices with:

    services.AddControllers()
      .AddJsonOptions(opt => opt.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverterWithAttributeSupport()));
    

    Finally, we need to register our ISchemaFilter in Swashbuckle, so also add the following also in ConfigureServices():

    services.AddSwaggerGen(c => {
      c.SchemaFilter();
    });
    

提交回复
热议问题