简体   繁体   中英

C# Swagger Generation for enum with default value

I have the api looks like the following:

public Task<IActionResult> GetAsync([FromRoute] string id, [FromQuery] Query select = Query.All)

For querys we only want to allow certain properties, listed in the Query enum as below:

    public enum Query
    {
        All,
        Property1,
        Property2
    }

I added

 services.AddSwaggerGen(c =>{c.DescribeAllEnumsAsStrings();})

in startup.cs, but this does not work for the default value, I get the following generated swagger, default value is 0 instead of a string:

     {
        "name": "selec",
        "in": "query",
        "description": "",
        "required": false,
        "type": "string",
        "default": 0, //NOT SHOWN AS STRING
        "enum": [
          "none",
          "property1",
          "property2"
        ]
      },

How should I make the default value show as a string?

Your project is automatically deserializing according to your application's serialization settings, the work around is to add the tag that changes the serialization of that specific property

[JsonConverter(typeof(StringEnumConverter))]

Edit: On the startup you can inject your json options to serialize the enums to strings like so:

 services.AddMvc().AddJsonOptions(options =>
                {
                    options.SerializerSettings.Converters.Add(new StringEnumConverter(true));
                });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM