Request Entity Coming as Null when upgrade to 3.1 c#

Viewed 169

EDITED

I am new here. So if this is a repeat question please forgive me.

We are having issue when we migrated to dotnet core 3.1 from 2.0. Explained as follows:

First our entity is like this

class Student {
      string StudentId 
}

So when we used our controller like this

 public async Task<IActionResult> GetStudentByIdAsync([FromBody] Student studentrequest)

we never got Studentrequest as null in 2.0 if we sent the entity as {"studentId":1} or {"studentId":"1"}

both worked fine.

But in 3.1 we are getting request as null if we give the request as {"studentId":1}. Our UI is based on this format and it is a separate external team. And we have lot of work based on this. So neither they nor us are willing to change.

One more point is that earlier we used addMvc() in Startup.cs, but now we are using addControllers(). Can this be a cause for this?

Can anyone help ? Thanks in advance.

1 Answers

Thanks to Dai's Comment :

What JSON deserialization library are you using? ASP.NET Core 3+ uses Microsoft's new JSON library instead of Newtonsoft.Json - I suspect it's refusing to match the camelCase studentId JSON property to your PascalCase StudentId class member. – Dai

I was able to understand that it was change in the implementation from NewtonSoft.Json as formatter in dotnet Core 2.0 to System.Text.Json in 3.X.

After looking around on a solution i found this post on medium.

The solution to prevent my error was to add Microsoft.AspNetCore.Mvc.NewtonsoftJson nuget to your solution and integrate the following or similar lines in your startup.cs configure method:

        _ = services.AddControllers(options =>
          {
              options.Filters.Add(typeof(WithHeaderHandlerAttribute));
          })
           .AddNewtonsoftJson(
            options =>
            options.SerializerSettings.ContractResolver = new
            CamelCasePropertyNamesContractResolver()).AddJsonOptions(options => options.JsonSerializerOptions.PropertyNameCaseInsensitive = true);

Hope this helps someone else.

Related