ASP.NET Core Json Enum Configuration

I’m working on a project which returns data back as json from a ASP.NET Core application. Part of this data is an enum and would return the interget index by default. However, that’s not helpful and I want it to return the string of the enum and not the index.

By adding the JsonOptions I’m able to override the default behavior.
.AddJsonOptions(opt => { opt.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter()); })

Orgiginal Code: (Startup.cs)

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}

Updated Code: (Startup.cs)

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddJsonOptions(opt => { opt.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter()); });
}

Leave a Comment

Your email address will not be published. Required fields are marked *