Enum type no longer working in .Net core 3.0 FromBody request object

For those who are looking for a snippet when using System.Text.Json

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers().AddJsonOptions(opt =>
    {
        opt.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
    });
}

.NET 6 / Top-level statement style

using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers()
    //convert strings to enums
    .AddJsonOptions(options =>
        options.JsonSerializerOptions.Converters
            .Add(new JsonStringEnumConverter()));

Support for serializing enums as strings already exist if you use the built-in JsonStringEnumConverter and pass that into the JsonSerializerOptions: https://docs.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonstringenumconverter?view=netcore-3.0

Here's a sample test that uses it: https://github.com/dotnet/corefx/blob/master/src/System.Text.Json/tests/Serialization/ReadScenarioTests.cs#L17


As of version 3.0, .NET Core no longer uses the third-party Newtonsoft.Json (Json.NET) by default but the new, built-in System.Text.Json (STJ) serializer - which is not as feature-rich as Json.NET, and of course has its own issues and learning curve to get the expected features.

If you’d like to switch back to the previous default of using Newtonsoft.Json, then you'll have to do the following:

  1. Install the Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package.

  2. In ConfigureServices() add a call to AddNewtonsoftJson()

public void ConfigureServices(IServiceCollection services) {
    //...

    services.AddControllers()
        .AddNewtonsoftJson(); //<--

    //...
}