.NET 6 Swagger: How to display enums as strings?
Asked Answered
D

1

9

I am trying to add enums as parameters for my Swagger endpoint but they are being displayed as integers:

swagger example

On the old .NET there was an option for Swagger option.DescribeAllEnumsAsStrings(); but I don't have it on .NET 6:

program code example

I tried adding:

options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());

but it is still not showing my enums as strings.

Diggins answered 26/9, 2022 at 14:23 Comment(2)
You add NewtonSoft support but add the System.Text.Json converter. The combination feels weird.Dallis
This was one of the suggestions I found and tried it. Still doesn't work..Diggins
M
20

I found the same issue here, and I test the workaround mentioned in the question in my side and it worked for me.

In Program.cs,

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

The code should look like:

using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);

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

enter image description here

Mol answered 27/9, 2022 at 2:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.