StringEnumSchemaFilter.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. using System.ComponentModel;
  2. using System.Reflection;
  3. using Microsoft.OpenApi.Any;
  4. using Microsoft.OpenApi.Models;
  5. using Swashbuckle.AspNetCore.SwaggerGen;
  6. namespace WebTemplate.ServerAspects.Swagger;
  7. /// <summary>
  8. /// This is a custom schema filter that updates the OpenApi definition of enums to specify their _string_ values
  9. /// instead of their numeric values and also adds a description from a <see cref="DescriptionAttribute"/> to each
  10. /// value if that attribute is present on the enum.
  11. /// </summary>
  12. // ReSharper disable once ClassNeverInstantiated.Global
  13. public class StringEnumSchemaFilter : ISchemaFilter
  14. {
  15. public void Apply(OpenApiSchema schema, SchemaFilterContext context)
  16. {
  17. var type = context.Type;
  18. if (type.IsEnum)
  19. {
  20. schema.Type = "string";
  21. schema.Format = null;
  22. schema.Enum = Enum.GetNames(type).Select(name => new OpenApiString(name)).Cast<IOpenApiAny>().ToList();
  23. var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static);
  24. var description = new StringWriter();
  25. foreach (var field in fields)
  26. {
  27. var descriptionAttribute = field.GetCustomAttribute<DescriptionAttribute>();
  28. if (descriptionAttribute != null)
  29. {
  30. description.WriteLine($"* `{field.Name}` - {descriptionAttribute.Description}");
  31. }
  32. }
  33. schema.Description = description.ToString();
  34. }
  35. }
  36. }