Swagger UI Web Api documentation Present enums as strings?

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

    This is not possible with standard OpenAPI. Enums are described only with their string values.

    Fortunately you can do it with some non-standard extensions that are utilized by your client generator.

    NSwag supports x-enumNames

    AutoRest supports x-ms-enum.

    Openapi-generator supports x-enum-varnames

    Other generators might support one of these extensions or have their own.

    To generate x-enumNames for NSwag create the following schema filter:

    public class EnumSchemaFilter : ISchemaFilter
    {
        public void Apply(OpenApiSchema schema, SchemaFilterContext context)
        {
            if (context.Type.IsEnum)
            {
                var array = new OpenApiArray();
                array.AddRange(Enum.GetNames(context.Type).Select(n => new OpenApiString(n)));
                // NSwag
                schema.Extensions.Add("x-enumNames", array);
                // Openapi-generator
                schema.Extensions.Add("x-enum-varnames", array);
            }
        }
    }
    

    And register it as:

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

提交回复
热议问题