I'm working with .NET minimal APIs and have encountered a problem with JSON serialization/deserialization behavior for enums. Despite my attempts to change the behavior to use strings instead of integers, Swashbuckle.AspNetCore's Swagger documentation continues to represent enums as integers.
using System.Text.Json.Serialization;
var builder = WebApplication.CreateBuilder(args);
// Docs: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-7.0#configure-json-deserialization-options-globally
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapPost("/api/v1/test", (TestRequest request) => Results.Ok(request));
app.Run();
public enum GridType
{
Arithmetic,
Geometric
}
public class TestRequest
{
public required string Name { get; init; }
public required GridType Type { get; set; }
}
But when Swagger UI opens, I still get an integer for the enum:
{
"name": "string",
"type": 0
}
The expected output is:
{
"name": "string",
"type": "Arithmetic"
}