9

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

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

然后我尝试使用以前工作的 Angular 8 发布 JSON 数据:

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

ASP.NET Core 3.0 API 中的模型是:

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 时我需要做其他事情吗?

4

2 回答 2

26

微软从 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

于 2020-05-22T12:15:06.537 回答
6

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

于 2019-11-15T22:28:52.443 回答