Swashbuckle.aspnetcore: StringEnumConverter applied via attribute to property of enum type has no effect.

Created on 13 Sep 2018  路  3Comments  路  Source: domaindrivendev/Swashbuckle.AspNetCore

I use Swashbuckle.AspNetCore 3.0.0.
I am not sure whether it is a bug per se, but when I have entity defined like:

public class MyDto
{
    [JsonConverter(typeof(StringEnumConverter))]
    public MyEnum Property {get;set;}
} 

Then description of Property has int type instead of string.

Most helpful comment

Decorate the enum itself with the StringEnumConverter instead of the property that uses it:

[JsonConverter(StringEnumConverter)]
public enum MyEnum
{
   ...
}

All 3 comments

You need to configure your Swagger generator in Startup.ConfigureServices() as follows:

C# services.AddSwaggerGen( swGenOptions => { swGenOptions.DescribeAllEnumsAsStrings(); }
See also
https://github.com/domaindrivendev/Swashbuckle.AspNetCore#customize-schema-for-enum-types.

This is for the description of the enum.
In order to actually serialize them as string in the output, I think you need in addition the JsonConverter attribute you are referring to.

The solution above works, but it is an all-or-nothing approach, and it doesn't change how enum properties are rendered when annotated with [JsonConverter].

I had to use a custom schema to properly render certain enums differently:

services.AddSwaggerGen(opt => {
  opt.MapType(typeof(MyEnum), () => new Schema()
  {
      Enum = Enum.GetNames(typeof(MyEnum)), // provide array of strings you want to represent your enum here
      Type = "string"
  });
});

Decorate the enum itself with the StringEnumConverter instead of the property that uses it:

[JsonConverter(StringEnumConverter)]
public enum MyEnum
{
   ...
}
Was this page helpful?
0 / 5 - 0 ratings