ASP.NET Core not binding arguments from body after upgrade to 3.1

Viewed 930

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;
}
2 Answers

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/

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.

Related