ASP.NET MVC Core API Serialize Enums to String
New System.Text.Json serialization
ASP.NET MVC Core 3.0 uses built-in JSON serialization. Use System.Text.Json.Serialization.JsonStringEnumConverter
(with "Json" prefix):
services
.AddMvc()
// Or .AddControllers(...)
.AddJsonOptions(opts =>
{
var enumConverter = new JsonStringEnumConverter();
opts.JsonSerializerOptions.Converters.Add(enumConverter);
})
More info here. The documentation can be found here.
If you prefer Newtonsoft.Json
You can also use "traditional" Newtonsoft.Json serialization:
Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson
And then:
services
.AddControllers()
.AddNewtonsoftJson(opts => opts
.Converters.Add(new StringEnumConverter()));
If you have a Minimal API
this will be useful:
using System.Text.Json.Serialization;
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(opt =>
{
opt.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
some addition:
if use Newtonsoft.Json
Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson
services
.AddControllers()
.AddNewtonsoftJson(options =>
options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter()));
options.SerializerSettings.Converters
SerializerSettings
is necessary