Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make enum serialization default to string in minimal API endpoints and Swagger?

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"
}
like image 453
nop Avatar asked Jan 22 '26 10:01

nop


1 Answers

There is an issue between MinimalApi and Swashbuckle Swagger you have to set the option in two different places:

builder.Services.ConfigureHttpJsonOptions(options =>
{
    options.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
builder.Services.Configure<Microsoft.AspNetCore.Mvc.JsonOptions>(options =>
{
    options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});

More info about the issue: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/2293

like image 195
ctyar Avatar answered Jan 24 '26 00:01

ctyar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!