3

I just upgraded an ASP.NET Core project from 2.2 to 3.1 and now my model binding doesn't work for POST requets. I read that the default JSON serializer changed from Newtonsoft.JSON to System.Text.Json in .NET Core 3. Could this be the reason?

My action and class look like this

[HttpPost]
public IActionResult Foo([FromBody]Bar req)
public class Bar
{
    public string Fiz;
    public int Buzz;
}
Thorkil Værge
  • 2,727
  • 5
  • 32
  • 48
  • 2
    If you suspect it is JSON serializer, you could install Newtonsoft JSON back https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.NewtonsoftJson/ – weichch Sep 12 '20 at 00:49
  • Do I need to do anything to make the ASP framework use this other JSON serialized? – Thorkil Værge Sep 12 '20 at 07:08
  • 2
    Yes, you will need to install the nuget package and add it like `services.AddControllers().AddNewtonsoftJson();`, check [this](https://dotnetcoretutorials.com/2019/12/19/using-newtonsoft-json-in-net-core-3-projects/) out. – weichch Sep 12 '20 at 10:47

2 Answers2

5

I just want to note that if modifying your models was not an option for you, then you can add JSON.NET Support back.

Simply install the following nuget package :

Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson

Then in your startup.cs, where you add MVC, do :

services.AddMvc().AddNewtonsoftJson();

And then you are back to using JSON.NET which was the serializer used for .NET Core 2.X projects.

https://dotnetcoretutorials.com/2019/12/19/using-newtonsoft-json-in-net-core-3-projects/

MindingData
  • 11,924
  • 6
  • 49
  • 68
3

Yes. The reason for this error is the new JSON library.

For some reason System.Text.Json does not populate fields, it only populates properties. So you need to change your class definition Bar to use properties

public class Bar
{
    public string Fiz { get; set; }
    public int Buzz { get; set; }
}

The serialization process uses the setter, so you cannot omit those.

Thorkil Værge
  • 2,727
  • 5
  • 32
  • 48
  • Luckily this fix can be done without changing anything else in the code, as the syntax to get and set fields and properties are the same. – Thorkil Værge Sep 11 '20 at 22:46