Mig*_*ura 8 c# asp.net-core asp.net-core-3.0 system.text.json
我将 ASP.NET Core 2.2 API 更新为 ASP.NET Core 3.0,并且我正在使用 System.Json:
services
.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddJsonOptions(x => {})
Run Code Online (Sandbox Code Playgroud)
然后我尝试使用 Angular 8 发布 JSON 数据,它之前工作过:
{
"name": "John"
"userId": "1"
}
Run Code Online (Sandbox Code Playgroud)
ASP.NET Core 3.0 API 中的模型是:
public class UserModel {
public String Name { get; set; }
public Int32? UserId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
API 控制器动作如下:
[HttpPost("users")]
public async Task<IActionResult> Create([FromBody]PostModel) {
}
Run Code Online (Sandbox Code Playgroud)
当我提交模型时,出现以下错误:
The JSON value could not be converted to System.Nullable[System.Int32].
Run Code Online (Sandbox Code Playgroud)
使用 System.Json 而不是 Newtonsoft 时,我需要做其他事情吗?
小智 21
Microsoft 已从 ASP.NET Core 3.0 中删除了 Json.NET 依赖项,现在使用 System.Text.Json 命名空间进行序列化、反序列化等。
您仍然可以将您的应用程序配置为使用 Newtonsoft.Json。为了这 -
安装 Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet 包
在 ConfigureServices() 中添加对 AddNewtonsoftJson()-的调用
services.AddControllers().AddNewtonsoftJson();
阅读更多https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/
此处通过 json 您为 UserId 传递了一个字符串值,但您的模型引用了一个 int32?UserId 的值。那么你的值是如何从字符串转换为 int32 的呢?