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:

and this:

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?
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:

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:

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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With