I am exploring Function App running on .net5
in the new isolated mode. I have HTTP triggered functions that I want to advertise via OpenAPI / Swagger.
To do so, I am using the package Microsoft.Azure.WebJobs.Extensions.OpenApi
in preview (0.7.2) to add the OpenAPI functionality to my Function App.
I am trying to have the enums
to be shown as string
in the OpenAPI page but I can't have it working properly.
Here is the setup in the Program.cs
file:
public static class Program
{
private static Task Main(string[] args)
{
IHost host = new HostBuilder()
.ConfigureAppConfiguration(configurationBuilder =>
{
configurationBuilder.AddCommandLine(args);
})
.ConfigureFunctionsWorkerDefaults(builder =>
{
builder.Services.Configure<JsonSerializerOptions>(options =>
{
options.Converters.Add(new JsonStringEnumConverter());
options.PropertyNameCaseInsensitive = true;
});
})
.ConfigureServices(services =>
{
// Registers any services.
})
.Build();
return host.RunAsync();
}
}
Here is the enum:
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum ApprovalContract
{
[EnumMember(Value = "Approved")]
Approved = 1,
[EnumMember(Value = "Rejected")]
Rejected = 2
}
And one of the class that uses it:
public sealed class DeletionResponseContract
{
[JsonPropertyName("approval")]
public ApprovalContract Approval { get; set; }
}
I replaced any references to Newtonsoft.Json
by System.Text.Json
everywhere.
Here is the output in the Swagger page:
Question
How can I serialize enum
as string
instead of int
in the Swagger page with an HTTP triggered Azure Function running on .net5
?
Update
I saw that the JsonStringEnumConverter
's constructor gives the indication to allow integer values:
public JsonStringEnumConverter(JsonNamingPolicy? namingPolicy = null, bool allowIntegerValues = true)
{
this._namingPolicy = namingPolicy;
this._converterOptions = allowIntegerValues ? EnumConverterOptions.AllowStrings | EnumConverterOptions.AllowNumbers : EnumConverterOptions.AllowStrings;
}
I modified my configuration like this, without any success:
builder.Services.Configure<JsonSerializerOptions>(options =>
{
options.Converters.Add(new JsonStringEnumConverter(allowIntegerValues: false));
options.PropertyNameCaseInsensitive = true;
});