Swagger UI Web Api documentation Present enums as strings?

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

    if anyone is interested i have modified the code to work with

    .NET CORE 3 and Swagger V5

        public class SwaggerAddEnumDescriptions : IDocumentFilter
    {
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            // add enum descriptions to result models
            foreach (var property in swaggerDoc.Components.Schemas.Where(x => x.Value?.Enum?.Count > 0))
            {
                IList propertyEnums = property.Value.Enum;
                if (propertyEnums != null && propertyEnums.Count > 0)
                {
                    property.Value.Description += DescribeEnum(propertyEnums, property.Key);
                }
            }
    
            // add enum descriptions to input parameters
            foreach (var pathItem in swaggerDoc.Paths.Values)
            {
                DescribeEnumParameters(pathItem.Operations, swaggerDoc);
            }
        }
    
        private void DescribeEnumParameters(IDictionary operations, OpenApiDocument swaggerDoc)
        {
            if (operations != null)
            {
                foreach (var oper in operations)
                {
                    foreach (var param in oper.Value.Parameters)
                    {
                        var paramEnum = swaggerDoc.Components.Schemas.FirstOrDefault(x => x.Key == param.Name);
                        if (paramEnum.Value != null)
                        {
                            param.Description += DescribeEnum(paramEnum.Value.Enum, paramEnum.Key);
                        }
                    }
                }
            }
        }
    
        private Type GetEnumTypeByName(string enumTypeName)
        {
            return AppDomain.CurrentDomain
                .GetAssemblies()
                .SelectMany(x => x.GetTypes())
                .FirstOrDefault(x => x.Name == enumTypeName);
        }
    
        private string DescribeEnum(IList enums, string proprtyTypeName)
        {
            List enumDescriptions = new List();
            var enumType = GetEnumTypeByName(proprtyTypeName);
            if (enumType == null)
                return null;
    
            foreach (OpenApiInteger enumOption in enums)
            {
                int enumInt = enumOption.Value;
    
                enumDescriptions.Add(string.Format("{0} = {1}", enumInt, Enum.GetName(enumType, enumInt)));
            }
    
            return string.Join(", ", enumDescriptions.ToArray());
        }
    }
    

提交回复
热议问题