15

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"
}
2
  • 1
    Please post a minimal reproducible example. Commented Jul 8, 2023 at 15:59
  • @GuruStron, hey, just edited my question with a minimal reproducible example. Commented Jul 8, 2023 at 16:54

1 Answer 1

37

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

Sign up to request clarification or add additional context in comments.

4 Comments

Updated the code. The new (available since .NET 7) ConfigureHttpJsonOptions method allows to skip the namespace.
Ohh, so that's why. Thanks
The reason why there's a need in Mvc.Json: "Swashbuckle.AspNetCore 6.x picks up changes from Microsoft.AspNetCore.Mvc.JsonOptions options. However, minimal API uses Microsoft.AspNetCore.Http.Json.JsonOptions. Therefore, both of them need to be configured so that Swagger schemas match the API output."
Finally! Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.