14

I have the following enum:

public enum TicketQuestionType
{
    General = 1,
    Billing = 2,
    TMS = 3,
    HOS = 4,
    DeviceManagement = 5
}

and model class:

public class TicketCreateApi
{
    public string Subject { get; set; }
    public TicketQuestionType QuestionType { get; set; } = TicketQuestionType.General;
    public TicketType Type { get; set; } = TicketType.Problem;
    public TicketStatus Status { get; set; } = TicketStatus.New;
    public TicketPriority Priority { get; set; } = TicketPriority.Normal;
    public string Description { get; set; }
    public List<string> Attachments { get; set; }
    public int? DeviceId { get; set; }
    public int? DriverId { get; set; }
}

my API method uses it:

Task<IActionResult> Create(TicketCreateApi model);

Swagger generates the following:

enter image description here

and this:

enter image description here

so, we can see only default value and no way to see available list of enum (names and values). I would like to show it. How to do it?

netotz
  • 193
  • 1
  • 4
  • 12
Oleg Sh
  • 8,496
  • 17
  • 89
  • 159

2 Answers2

32

we can see only default value and no way to see available list of enum (names and values). I would like to show it. How to do it?

To display the enums as strings in swagger, you configure the JsonStringEnumConverter, adding the following line in ConfigureServices :

        services.AddControllers().AddJsonOptions(options =>
            options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));

The output as below:

enter image description here

If you want to display the enums as stings and int values, you could try to create a EnumSchemaFilter to change the schema. code as below:

public class EnumSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema model, SchemaFilterContext context)
    {
        if (context.Type.IsEnum)
        {
            model.Enum.Clear();
            Enum.GetNames(context.Type)
                .ToList()
                .ForEach(name => model.Enum.Add(new OpenApiString($"{Convert.ToInt64(Enum.Parse(context.Type, name))} = {name}")));
        }
    }
}

Configure the SwaggerGen to use above ShemaFilter.

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo
            {
                Version = "v1",
                Title = "ToDo API",
                Description = "A simple example ASP.NET Core Web API",
                TermsOfService = new Uri("https://example.com/terms"),
                Contact = new OpenApiContact
                {
                    Name = "Shayne Boyer",
                    Email = string.Empty,
                    Url = new Uri("https://twitter.com/spboyer"),
                },
                License = new OpenApiLicense
                {
                    Name = "Use under LICX",
                    Url = new Uri("https://example.com/license"),
                }
            });
              
            c.SchemaFilter<EnumSchemaFilter>();
        });

The result like this:

enter image description here

Zhi Lv
  • 18,845
  • 1
  • 19
  • 30
  • 2
    JsonStringEnumConverter affects the way the entire system handles enumerators, making them receive string instead of integer. EnumSchemaFilter breaks the functionality of calls with enumerators through the swagger. – William Magno May 19 '22 at 13:42
  • Clean and easy implementation. Better than add the attribute in each Enum +1. Works perfectly in .Net 6 Core – MiBol Aug 15 '22 at 11:41
1

I tried EnumSchemaFilter. I got some error every time i submited the request. Because the serialize enum string to int

I used this code block and i hope it works

services.AddControllersWithViews()
                    .AddJsonOptions(
                        opts =>
                        {
                            var enumConverter = new JsonStringEnumConverter();
                            opts.JsonSerializerOptions.Converters.Add(enumConverter);
                        });
hoangsnowy
  • 256
  • 1
  • 4