Swashbuckle.AspNetCore: Enum string converter is not respected using .NET 6 minimal API

Using Swashbuckle.AspNetCore 6.2.3 with ASP.NET 6 minimal API, I have configured JSON serializer options per the docs.

services.Configure<JsonOptions>(options =>
{
    options.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
    options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
    options.SerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
});

However, Swagger UI still reports enums as ints unless I add also use AddControllers().AddJsonOptions():

services.AddControllers()
	.AddJsonOptions(options =>
	{
            options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
            options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
            options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;	
        });

Once the second block is added, the swagger UI output references the enum string values as expected. As far as I know, the latter simply does the former under the hood, but there seems to be some order of operations affecting the schema generation here?

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Reactions: 35
  • Comments: 28 (1 by maintainers)

Most upvoted comments

I ran into the same problem and my colleague suggested the following as a workaround, which works for me:

using Microsoft.AspNetCore.Http.Json;
using MvcJsonOptions = Microsoft.AspNetCore.Mvc.JsonOptions;
.....
builder.Services.Configure<JsonOptions>(o => o.SerializerOptions.Converters.Add(new JsonStringEnumConverter()));
builder.Services.Configure<MvcJsonOptions>(o => o.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));

You can always use NewtonsoftJson it is in nuget <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.2" />

here are my settings .AddNewtonsoftJson(options => { options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; options.SerializerSettings.Converters.Add(new StringEnumConverter()); options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc; });

The following method was used to collect the Serializer settings in one place.

builder.Services.TryAddTransient<ISerializerDataContractResolver>(s =>
{
    var httpJsonOptions = s.GetRequiredService<IOptions<Microsoft.AspNetCore.Http.Json.JsonOptions>>();
    var serializerOptions = httpJsonOptions.Value.SerializerOptions;
    return new JsonSerializerDataContractResolver(serializerOptions);
});

builder.Services.AddSwaggerGen(options =>
{
    // ...
});

I managed to get this fully working for minimal API scenarios by decorating the enum type itself with JsonConverterAttribute.

Tested on NET7 and NET8 RC1:

using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Mvc;

// var builder = WebApplication.CreateSlimBuilder(args); -NET8-
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// OK
app.MapPost("postDemo", (RequestDto dto) => TypedResults.Ok(new ResponseDto(dto.Enum)));

// Does not work, query param schema is string
app.MapGet("getDemo1", (DemoEnum? enumParameter) => TypedResults.Ok(new ResponseDto(enumParameter)));

// OK
app.MapGet("getDemo2", ([FromQuery] DemoEnum? enumParameter) => TypedResults.Ok(new ResponseDto(enumParameter)));

// OK
app.MapGet("getDemo3", ([AsParameters] Parameters parameters) => TypedResults.Ok(new ResponseDto(parameters.EnumParameter)));

app.UseSwagger();
app.UseSwaggerUI();
app.Run();

public struct Parameters
{
    [FromQuery]
    public DemoEnum? EnumParameter { get; set; }
}

public sealed record RequestDto(DemoEnum? Enum);
public sealed record ResponseDto(DemoEnum? Enum);

// [JsonConverter(typeof(JsonStringEnumConverter<DemoEnum>))] -NET8-
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum DemoEnum
{
    FirstValue,
    SecondValue,
}

Swashbuckle.AspNetCore 6.4.0 picks up changes from “Microsoft.AspNetCore.Mvc.JsonOptions” options. However, minimal APIs are using “Microsoft.AspNetCore.Http.Json.JsonOptions”. Therefore, both of them needs to be configured for Swagger schemas to match the API output.

It would be nice if Swashbuckle can be configured to use “Microsoft.AspNetCore.Http.Json.JsonOptions”.

A comment to prevent this one from closing due to inactivity, as I believe it’s still applicable and does have all the information for the reproduction.

@wrkntwrkn and @stvwndr helped lead me to the workaround that I’m using:

builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(options =>
{
	options.SerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter());
});
builder.Services.Configure<Microsoft.AspNetCore.Mvc.JsonOptions>(options =>
{
	options.JsonSerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter());
});

Thank you, this works as expected!

@wrkntwrkn and @stvwndr helped lead me to the workaround that I’m using:

builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(options =>
{
	options.SerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter());
});
builder.Services.Configure<Microsoft.AspNetCore.Mvc.JsonOptions>(options =>
{
	options.JsonSerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter());
});

To anyone facing a similar issue as me, make sure you have the right namespace when registerting your serializer globally.

NOT - Microsoft.AspNetCore.Mvc - JsonOptions YES - Microsoft.AspNetCore.Http.Json - JsonOptions

It was in the docs but i missed it when migrating to minimal api’s since the namings are ver similar.

Looking into this some more, it looks like the problem may be in SwaggerGenServiceCollectionExtensions.cs, line 34:

#if (!NETSTANDARD2_0)
                var serializerOptions = s.GetService<IOptions<JsonOptions>>()?.Value?.JsonSerializerOptions
                    ?? new JsonSerializerOptions();
#else
                var serializerOptions = new JsonSerializerOptions();
#endif

The problem here is that the JsonOptions type is pulled from the Microsoft.AspNetCore.Mvc namespace while .NET 6 minimal APIs are documented to use JsonOptions from the Microsoft.AspNetCore.Http.Json namespace which this code seems blissfully unaware of. Not sure what the path forward is.

The below workaround works on the swagger schema.

builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(options =>
{
	options.SerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter());
});
builder.Services.Configure<Microsoft.AspNetCore.Mvc.JsonOptions>(options =>
{
	options.JsonSerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter());
});

However, I had to use AddContollers to get it working with the swagger example.

builder.Services.AddControllers()
    .AddJsonOptions(options =>
        options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));

Has anyone been able to get it working with the swagger example without adding AddControllers?

Stumbled upon this issue while debugging this issue. I can confirm the suspicion of @soligto . Mvc.JsonOptions is never null. Http.Json.JsonOptions are never considered at all.

Still an issue in version 8.1.0 on net8.0. Here’s a minimal project that reproduces the issue: https://github.com/fmelink/swashbucklerenumfail

Isn’t it because AspNetCore.Mvc.JsonOptions.JsonSerializerOptions is never null?

https://github.com/dotnet/dotnet/blob/main/src/aspnetcore/src/Mvc/Mvc.Core/src/JsonOptions.cs#L35

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/src/Swashbuckle.AspNetCore.SwaggerGen/DependencyInjection/SwaggerGenServiceCollectionExtensions.cs#L81

#if !NETSTANDARD2_0
                serializerOptions =
                    _serviceProvider.GetService<IOptions<AspNetCore.Mvc.JsonOptions>>()?.Value?.JsonSerializerOptions
#if NET8_0_OR_GREATER
                    ?? _serviceProvider.GetService<IOptions<AspNetCore.Http.Json.JsonOptions>>()?.Value?.SerializerOptions
#endif
#if NET7_0_OR_GREATER
                    ?? JsonSerializerOptions.Default;
#else
                    ?? new JsonSerializerOptions();
#endif

This code will never get SerializerOptions from AspNetCore.Http.Json.JsonOptions.

[JsonConverter(typeof(JsonStringEnumConverter))]
public enum DemoEnum

Thanks this works for me. But of course decorating all enums with that is far from ideal, it would be nice if ASPNET respected the serializer converter.

I’m using .Net7, and this issue still exists. Here’s my project setup:

<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.5" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.18.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />

Here’s my code:

public record DemoObject
{
    [JsonConverter(typeof(JsonStringEnumConverter))]
    public DemoEnum DemoProperty { get; init; }
}

public enum DemoEnum : int { PlanA = 9, PlanB = 13 }

[Route("api/[controller]")]
[ApiController]
public class DemoController : ControllerBase
{
    [HttpGet("demo")]
    public DemoObject DemoAction() => new() { DemoProperty = DemoEnum.PlanB };
}

As you can see, I decorated enum field with JsonConverterAttribute, using JsonStringEnumConverter as attribute parameter. If I hit “execute”, I can get PlanB in response as expected. However, when generating “Example value”, the json serializer serialized enum field as integer, as the screenshot below demonstrates.

image

I can confirm that the issue still persists for me too.

Looking into this some more, it looks like the problem may be in SwaggerGenServiceCollectionExtensions.cs, line 34:

#if (!NETSTANDARD2_0)
                var serializerOptions = s.GetService<IOptions<JsonOptions>>()?.Value?.JsonSerializerOptions
                    ?? new JsonSerializerOptions();
#else
                var serializerOptions = new JsonSerializerOptions();
#endif

The problem here is that the JsonOptions type is pulled from the Microsoft.AspNetCore.Mvc namespace while .NET 6 minimal APIs are documented to use JsonOptions from the Microsoft.AspNetCore.Http.Json namespace which this code seems blissfully unaware of. Not sure what the path forward is.

Maybe the best option would be to have something like this: builder.Services.AddSwaggerGen(options => options.EnableMinimalApi());

Just noting that another approach here is the below lines:

    builder.Services.AddTransient<ISerializerDataContractResolver>(_ => new JsonSerializerDataContractResolver(
        new JsonSerializerOptions {
             // set whatever default options for JSON serialization you want like enums, PropertyNamingPolicy, or whatever
        }
    ));

I think the comment at https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/2293#issuecomment-991870685 is correct that this is the bug because of this code: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/8f363f7359cb1cb8fa5de5195ec6d97aefaa16b3/src/Swashbuckle.AspNetCore.SwaggerGen/DependencyInjection/SwaggerGenServiceCollectionExtensions.cs#L33-L43

The code in the #else block just uses the default JsonSerializerOptions if the code isn’t NETSTANDARD2_0 which includes net8.0.

I managed to get this fully working for minimal API scenarios by decorating the enum type itself with JsonConverterAttribute.

Tested on NET7 and NET8 RC1:

using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Mvc;

// var builder = WebApplication.CreateSlimBuilder(args); -NET8-
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// OK
app.MapPost("postDemo", (RequestDto dto) => TypedResults.Ok(new ResponseDto(dto.Enum)));

// Does not work, query param schema is string
app.MapGet("getDemo1", (DemoEnum? enumParameter) => TypedResults.Ok(new ResponseDto(enumParameter)));

// OK
app.MapGet("getDemo2", ([FromQuery] DemoEnum? enumParameter) => TypedResults.Ok(new ResponseDto(enumParameter)));

// OK
app.MapGet("getDemo3", ([AsParameters] Parameters parameters) => TypedResults.Ok(new ResponseDto(parameters.EnumParameter)));

app.UseSwagger();
app.UseSwaggerUI();
app.Run();

public struct Parameters
{
    [FromQuery]
    public DemoEnum? EnumParameter { get; set; }
}

public sealed record RequestDto(DemoEnum? Enum);
public sealed record ResponseDto(DemoEnum? Enum);

// [JsonConverter(typeof(JsonStringEnumConverter<DemoEnum>))] -NET8-
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum DemoEnum
{
    FirstValue,
    SecondValue,
}

Thanks, this also works in NET6!

I ran into the same problem and my colleague suggested the following as a workaround, which works for me:

using Microsoft.AspNetCore.Http.Json;
using MvcJsonOptions = Microsoft.AspNetCore.Mvc.JsonOptions;
.....
builder.Services.Configure<JsonOptions>(o => o.SerializerOptions.Converters.Add(new JsonStringEnumConverter()));
builder.Services.Configure<MvcJsonOptions>(o => o.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));

Is this workaround working on version net6.0 (6.0.100)? Dosen’t seem to work for me. Still get a serializer exception. Using System.Text.Json 6.0.2

An unhandled exception has occurred while executing the request. Microsoft.AspNetCore.Http.BadHttpRequestException: Failed to read parameter "MessageRequest messageRequest" from the request body as JSON. ---> System.Text.Json.JsonException: The JSON value could not be converted to Domain.Shared.Enums.MessageTypeEnum. Path: $.messageType | LineNumber: 2 | BytePositionInLine: 28.

For now im passing in HttpRequest httpRequest and deserializing it myself, which is not ideal/clean.