Search code examples
c#asp.net-coreswagger.net-6.0

.Net 6 Minimal API Define Enum Parameter In Swagger


Is there a way to describe an enum in Swagger using a minimal API like there is for a controller-based API?

I have a simple enum:

public enum GeometryType
{
    WKT,
    GeoJson
}

and an endpoint:

app.MapGet("/geometry", (GeometryType? geometryType) =>
{

};

But the parameter is defined as a string in my swagger page and therefore I'm not getting the nice dropdown with the available options like I would with a controller:

{
 "name": "geometryType",
  "in": "query",
  "schema": {
  "type": "string"
 }
}

I've tried explicitly mapping the type in my Swagger setup:

services.AddSwaggerGen(options =>
{
    options.MapType<GeometryType>(() => new OpenApiSchema { Type = "integer", Format = "int32", Enum = Enum.GetNames(typeof(GeometryType)).Select(name => new OpenApiString(name)).Cast<IOpenApiAny>().ToList() });
});

But that type never shows up in my swagger.json page, which leads me to believe its got something to do with the way .Net is creating that endpoint.


Solution

  • Firstly, you need be sure if it works in normal web api. If not working, be sure add the [JsonConverter(typeof(JsonStringEnumConverter))] to the enum

    [JsonConverter(typeof(JsonStringEnumConverter))]
       public enum GeometryType
       {
           WKT,
           GeoJson
       }
    

    or globally add the JsonStringEnumConverter in Program.cs:

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

    Then, you must define [FromQuery] before the parameter:

    app.MapGet("/geometry", ([FromQuery] GeometryType? geometryType) =>
    {
    
    });
    

    The json would be:

    "parameters": [
              {
                "name": "geometryType",
                "in": "query",
                "schema": {
                  "enum": [
                    "WKT",
                    "GeoJson"
                  ],
                  "type": "string"
                }
              }
            ],
    

    Result: enter image description here