.netenumsswaggerdocumentation

How to receive Enum as String in a Dotnet API?


I have a dotnet API application documented with swagger. In one of my end-points I receive a DTO like this:

 public class CreateCooperativeUserDTO
{
    [Required]
    public required string Name { get; set; }

    [Required]
    public required DateTime BirthDate { get; set; }

    [Required]
    public required DateTime AdmissionDate { get; set; }

    [Required]
    public required string BadgeName { get; set; }

    [Required]
    [JsonConverter(typeof(JsonStringEnumConverter<Race>))]
    public required Race Race { get; set; }
}

This DTO has a property called Race that is a Enum but in my swagger documentation they are represented as a array of Integer.

Example of schema

I would like to receive they as a array of string. How i can do this?


Solution

  • I was able to expose the Enum as string configuring the method JsonOptions on extension method AddControllers in Program.cs like the follow code:

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