EnumSchemaFilter.cs 1.0 KB

123456789101112131415161718192021222324252627
  1. using Microsoft.OpenApi.Any;
  2. using Microsoft.OpenApi.Models;
  3. using Swashbuckle.AspNetCore.SwaggerGen;
  4. namespace AipGateway.API.Extensions
  5. {
  6. public class EnumSchemaFilter : ISchemaFilter
  7. {
  8. public void Apply(OpenApiSchema model, SchemaFilterContext context)
  9. {
  10. if (context.Type.IsEnum)
  11. {
  12. model.Enum.Clear();
  13. var names = Enum.GetNames(context.Type).ToList();
  14. names.ForEach(name => model.Enum.Add(new OpenApiString($"{GetEnumIntegerValue(name, context)} = {name}")));
  15. // the missing piece that will make sure that the new schema will not replace the mock value with a wrong value
  16. // this is the default behavior - the first possible enum value as a default "example" value
  17. model.Example = new OpenApiInteger(GetEnumIntegerValue(names.First(), context));
  18. }
  19. }
  20. private int GetEnumIntegerValue(string name, SchemaFilterContext context) => Convert.ToInt32(Enum.Parse(context.Type, name));
  21. }
  22. }