11

I updated an ASP.NET Core 2.2 API to ASP.NET Core 3.0 and I am using System.Json:

services
  .AddMvc()
  .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
  .AddJsonOptions(x => {}) 

I then tried to post JSON data using Angular 8, which was working before:

{
  "name": "John"
  "userId": "1"
}

The model in the ASP.NET Core 3.0 API is:

public class UserModel {
  public String Name { get; set; }
  public Int32? UserId { get; set; } 
}

And the API Controller action is as follows:

[HttpPost("users")]
public async Task<IActionResult> Create([FromBody]PostModel) { 
}

When I submit the model I get the following error:

The JSON value could not be converted to System.Nullable[System.Int32]. 

Do I need to do something else when using System.Json instead of Newtonsoft?

Daniel A. White
  • 181,601
  • 45
  • 354
  • 430
Miguel Moura
  • 32,822
  • 74
  • 219
  • 400

2 Answers2

29

Microsoft has removed Json.NET dependency from ASP.NET Core 3.0 onwards and using System.Text.Json namespace now for serialization, deserialization and more.

You can still configure your application to use Newtonsoft.Json. For this -

  1. Install Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package

  2. In ConfigureServices() add a call to AddNewtonsoftJson()-

    services.AddControllers().AddNewtonsoftJson();

Read more on https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/

https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to

Sandeep Kumar
  • 525
  • 5
  • 6
  • 2
    This is the more useful answer even if the accepted answer is correct for the question. – Mukus Oct 30 '20 at 00:38
7

Here Via the json you pass a string value for UserId but your model refer a int32? value for UserId. Then how your value convert from string to int32?

MK Vimalan
  • 1,115
  • 12
  • 26