Swagger UI Web Api documentation Present enums as strings?

后端 未结 20 2014
半阙折子戏
半阙折子戏 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:40

    in .net core 3.1 & swagger 5.0.0 :

    using System.Linq;
    using Microsoft.OpenApi.Any;
    using Microsoft.OpenApi.Models;
    using Swashbuckle.AspNetCore.SwaggerGen;
    
    namespace WebFramework.Swagger
    {
        public class EnumSchemaFilter : ISchemaFilter
        {
            public void Apply(OpenApiSchema schema, SchemaFilterContext context)
            {
                if (context.Type.IsEnum)
                {
                    var enumValues = schema.Enum.ToArray();
                    var i = 0;
                    schema.Enum.Clear();
                    foreach (var n in Enum.GetNames(context.Type).ToList())
                    {
                        schema.Enum.Add(new OpenApiString(n + $" = {((OpenApiPrimitive)enumValues[i]).Value}"));
                        i++;
                    }
                }
            }
        }
    
    }
    

    and in Startup.cs :

    services.AddSwaggerGen(options =>
                {
                    #region  EnumDesc
                    options.SchemaFilter();
                    #endregion
                });
    

提交回复
热议问题