3

We are implementing a .NET Core 3.1 API and we are using Microsoft.AspNetCore.Mvc.NewtonsoftJson according to this doc. We are dealing with enums and we need the string representation instead of the integers. We are doing it using the JsonConverter attribute like this:

[JsonProperty("region")]
[JsonConverter(typeof(StringEnumConverter))]
public Region Region { get; set; }

We are trying to do it globally from the Startup.cs like below :

services.AddControllers().AddNewtonsoftJson(opts => opts.SerializerSettings.Converters.Add(new StringEnumConverter()));

If we do that, the Cosmos DB is complaining with

"PartitionKey extracted from document doesn't match the one specified in the header"

So we tried removing all the attributes except by the region one. All the other enums that don't have the attribute are stored as strings correctly, but the region still needs the attribute to work. Any clue why is this happening and how to solve it?

user33276346
  • 1,501
  • 1
  • 19
  • 38
  • `AddNewtonsoftJson()` only affects the default behavior of asp.net core JSON serializing and model binding, it doesn't affect the behavior of Json.NET *standalone* or other apps. To do that see [Set default global json serializer settings](https://stackoverflow.com/q/21815759/3744182). – dbc Jun 29 '20 at 20:03
  • That assumes that CosmosDB is using Json.NET's global settings. (If you manually construct a serializer using [`JsonSerializer.Create()`](https://www.newtonsoft.com/json/help/html/Overload_Newtonsoft_Json_JsonSerializer_Create.htm) instead of `JsonSerializer.CreateDefault()` the global defaults are ignored.) Can you please [edit] your question to share a [mcve] showing how to generate the Cosmos DB error? – dbc Jun 29 '20 at 20:12
  • It would be cumbersome to share the code, and that is part of the reason of the problem that you helped me to realize of. I have an .NET Core API, so I don't see how to configure Json.NET standalone on a more high level than the Startup. HOWEVER, I've realized that the attributes are used in clases from a different project ‍♂️. I plan this weekend, to add this explanation as an answer to maybe help others to pay attention to this, unless you can give more insights. Thanks dbc! – user33276346 Jun 30 '20 at 01:55

1 Answers1

2

In netcore 3.1 or higher, you can use JsonStringEnumConverter:

 var options = new JsonSerializerOptions
        {            
            Converters = { new JsonStringEnumConverter() },
             //other options
        };

Try Example online

M.Hassan
  • 10,282
  • 5
  • 65
  • 84