We had an ASP.NET Core 5 Web API backend alongside a ReactJS UI app. In startup we instantiated the json framework the following way:
services.AddControllers()
.AddNewtonsoftJson()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
It was working well alongside "JsonPropertyName" attributes, i.e. the following property was correctly received in javascript as interfaceId
:
[JsonPropertyName("interfaceId")]
public long INTERFACE_ID { get; set; }
Eventually, some guy decided it would be a good idea to upgrade the projects to .NET 7, which caused json serialization to stop working. Above example was received in Javascript as interfacE_ID
(the lower and uppercase characters are exactly that way). The same way, json objects sent from Javascript to Web API stopped being auto serialized into C# objects (getting a http 400 response), so I have to switch my controller declaration from
public IActionResult Insert([FromBody] Rol entity) => this.Ok(this.service.Insert(entity));
to
public IActionResult Insert([FromBody] JToken entity) => this.Ok(this.service.Insert(entity.ToObject<Rol>()));
I have seen in this post JSON.Net serializer ignoring JsonProperty? that, probably, could be a conflict on json.net (or newtonsoft.json) versions, so I cleaned everything and updated all nuget packages, removing System.Text.Json
and Newtonsoft.Json
packages, keeping only Microsoft.AspNetCore.Mvc.NewtonsoftJson
.
I also tried to apply explicit json naming converters like those proposed in this article https://devblogs.microsoft.com/dotnet/system-text-json-in-dotnet-7/, but at the moment I achieved nothing.
As I’m not an expert in .net7, I would like to know where could be the problem located or if I’m missing a configuration step required for the new framework.
Thanks
Edit: Thank you very much to everyone
Attribute modification proposed by @Serge worked, so Newtonsoft.Json was the serializer which handled the requests.
So, I removed .AddNewtonsoftJson()
from my startup.cs and the output serialization (web api to Javascript) began working well again.
I’m still facing input serialization issues (HTTP 400), I guess related to .net7 nullable policies, so I’m looking for a way to get the proper validation error which triggers the HTTP 400 response
2
Answers
The answer was a mix between al of your responses. I, finally, decided to remove Newtonsoft.Json, keeping System.Text.Json and adapt my model classes to avoid .net7 null properties validation
Just fix the name attribute from System.Text.Json to Newtonsoft.Json
and since you are using Net7 in some cases to avoid a validation error (400) would be usefull