Swagger UI Web Api documentation Present enums as strings?

后端 未结 20 2078
半阙折子戏
半阙折子戏 2020-11-27 11:31

Is there a way to display all enums as their string value in swagger instead of their int value?

I want to be able to submit POST actions and put enums according to

20条回答
  •  孤街浪徒
    2020-11-27 11:51

    For ASP.NET Core 3 with the Microsoft JSON library (System.Text.Json)

    In Startup.cs/ConfigureServices():

    services
        .AddControllersWithViews(...) // or AddControllers() in a Web API
        .AddJsonOptions(options => 
            options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
    

    For ASP.NET Core 3 with the Json.NET (Newtonsoft.Json) library

    Install the Swashbuckle.AspNetCore.Newtonsoft package.

    In Startup.cs/ConfigureServices():

    services
        .AddControllersWithViews(...)
        .AddNewtonsoftJson(options => 
            options.SerializerSettings.Converters.Add(new StringEnumConverter()));
    // order is vital, this *must* be called *after* AddNewtonsoftJson()
    services.AddSwaggerGenNewtonsoftSupport();
    

    For ASP.NET Core 2

    In Startup.cs/ConfigureServices():

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

    Pre-ASP.NET Core

    httpConfiguration
        .EnableSwagger(c => 
            {
                c.DescribeAllEnumsAsStrings();
            });
    

提交回复
热议问题