JSON 值无法转换为 System.Nullable[System.Int32]

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

我将 ASP.NET Core 2.2 API 更新为 ASP.NET Core 3.0,我正在使用 System.Json:

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

然后我尝试使用 Angular 8 post JSON 数据,它在之前工作:

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

ASP.NETCore 3.0API中的模型是:

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

而API控制器动作如下:

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

提交模型时出现以下错误:

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

使用 System.Json 而不是 Newtonsoft 时,我还需要做其他事情吗?

这里通过 json 您为 UserId 传递了一个字符串值,但您的模型引用了一个 int32? UserId 的值。那么你的值如何从字符串转换为 int32?

Microsoft 已从 ASP.NET Core 3.0 中移除 Json.NET 依赖项,并使用 System.Text.Json 命名空间进行序列化、反序列化等。

您仍然可以配置您的应用程序以使用 Newtonsoft.Json。为此-

  1. 安装Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet 包

  2. 在 ConfigureServices() 中添加对 AddNewtonsoftJson() 的调用-

    services.AddControllers().AddNewtonsoftJson();

阅读更多关于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