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

1

8

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"
}
Apocynaceous answered 8/7, 2023 at 15:55 Comment(2)
Please post a minimal reproducible example.Footpace
@GuruStron, hey, just edited my question with a minimal reproducible example.Apocynaceous
B
20

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

Badmouth answered 8/7, 2023 at 17:11 Comment(2)
Updated the code. The new (available since .NET 7) ConfigureHttpJsonOptions method allows to skip the namespace.Footpace
Ohh, so that's why. ThanksApocynaceous

© 2022 - 2024 — McMap. All rights reserved.