从 .NET Core 2.2 迁移到 3.0-preview-9 后模型绑定停止工作
Model binding stopped working after migrating from .NET Core 2.2 to 3.0-preview-9
我有一个 Angular 前端应用程序和一个 ASP.NET 核心后端应用程序。一切都很好,直到我决定从 ASP.NET Core 2.2 迁移到 3.0-preview-9。
比如我有一个DTO class:
public class DutyRateDto
{
public string Code { get; set; }
public string Name { get; set; }
public decimal Rate { get; set; }
}
还有一个例子JSON请求:
{
"name":"F",
"code":"F",
"rate":"123"
}
在迁移之前,这是一个有效的请求,因为 123
被解析为小数。但是现在,在迁移之后,我收到此正文的 HTTP 400 错误:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|3293cead-4a35656a3ae5e95b.",
"errors": {
"$.rate": [
"The JSON value could not be converted to System.Decimal. Path: $.rate | LineNumber: 0 | BytePositionInLine: 35."
]
}
}
此外,它没有命中我的方法的第一行——它之前抛出,可能是在模型绑定期间。
但是,如果我发送以下内容:
{
"name":"F",
"code":"F",
"rate":123
}
一切正常。但这意味着我需要更改到目前为止我写的每一个请求。对于所有其他数据类型(int
、bool
、...)也是如此。
有谁知道我如何避免这种情况并在不更改我的请求的情况下使其正常工作?
ASP.NET Core 3 使用 System.Text.Json
而不是 Newtonsoft.Json
(又名 JSON.NET)来处理 JSON。 JSON.NET 支持从字符串解析为小数,但 System.Text.Json
不支持。在这个阶段 最简单 的事情是切换回使用 JSON.NET,如 docs:
中所述
- Add a package reference to Microsoft.AspNetCore.Mvc.NewtonsoftJson.
Update Startup.ConfigureServices
to call AddNewtonsoftJson
.
services.AddMvc()
.AddNewtonsoftJson();
将小数作为 JSON 数字传递会更正确,但很明显这不适合您。
我有一个 Angular 前端应用程序和一个 ASP.NET 核心后端应用程序。一切都很好,直到我决定从 ASP.NET Core 2.2 迁移到 3.0-preview-9。
比如我有一个DTO class:
public class DutyRateDto
{
public string Code { get; set; }
public string Name { get; set; }
public decimal Rate { get; set; }
}
还有一个例子JSON请求:
{
"name":"F",
"code":"F",
"rate":"123"
}
在迁移之前,这是一个有效的请求,因为 123
被解析为小数。但是现在,在迁移之后,我收到此正文的 HTTP 400 错误:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|3293cead-4a35656a3ae5e95b.",
"errors": {
"$.rate": [
"The JSON value could not be converted to System.Decimal. Path: $.rate | LineNumber: 0 | BytePositionInLine: 35."
]
}
}
此外,它没有命中我的方法的第一行——它之前抛出,可能是在模型绑定期间。
但是,如果我发送以下内容:
{
"name":"F",
"code":"F",
"rate":123
}
一切正常。但这意味着我需要更改到目前为止我写的每一个请求。对于所有其他数据类型(int
、bool
、...)也是如此。
有谁知道我如何避免这种情况并在不更改我的请求的情况下使其正常工作?
ASP.NET Core 3 使用 System.Text.Json
而不是 Newtonsoft.Json
(又名 JSON.NET)来处理 JSON。 JSON.NET 支持从字符串解析为小数,但 System.Text.Json
不支持。在这个阶段 最简单 的事情是切换回使用 JSON.NET,如 docs:
- Add a package reference to Microsoft.AspNetCore.Mvc.NewtonsoftJson.
Update
Startup.ConfigureServices
to callAddNewtonsoftJson
.services.AddMvc() .AddNewtonsoftJson();
将小数作为 JSON 数字传递会更正确,但很明显这不适合您。