[英]Model binding stopped working after migrating from .NET Core 2.2 to 3.0-preview-9
I have an Angular front-end app and an ASP.NET Core back-end app.我有一个 Angular 前端应用程序和一个 ASP.NET Core 后端应用程序。 Everything was fine until I decided to migrate from ASP.NET Core 2.2 to 3.0-preview-9.一切都很好,直到我决定从 ASP.NET Core 2.2 迁移到 3.0-preview-9。
For example, I have a DTO class:例如,我有一个 DTO 类:
public class DutyRateDto
{
public string Code { get; set; }
public string Name { get; set; }
public decimal Rate { get; set; }
}
And an example JSON request:以及一个示例 JSON 请求:
{
"name":"F",
"code":"F",
"rate":"123"
}
Before migration, this was a valid request because 123
was parsed as a decimal.在迁移之前,这是一个有效的请求,因为123
被解析为十进制。 But now, after migration, I am getting an HTTP 400 error with this body:但是现在,在迁移后,我收到此正文的 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."
]
}
}
In addition, it doesn't hit the first line of my method—it is thrown before, probably during model binding.此外,它没有碰到我方法的第一行——它在之前被抛出,可能是在模型绑定期间。
If I send the following, however:但是,如果我发送以下内容:
{
"name":"F",
"code":"F",
"rate":123
}
Everything works fine.一切正常。 But this means that I need to change every request I have written so far.但这意味着我需要更改到目前为止我写的每个请求。 The same thing is true with all other data types ( int
, bool
, …).所有其他数据类型( int
, bool
,...)也是如此。
Does anybody know how I can avoid this and make it work without changing my requests?有谁知道我可以如何避免这种情况并使其工作而不改变我的请求?
ASP.NET Core 3 uses System.Text.Json
instead of Newtonsoft.Json
(aka JSON.NET) for handling JSON. ASP.NET Core 3 使用System.Text.Json
而不是Newtonsoft.Json
(又名 JSON.NET)来处理 JSON。 JSON.NET supports parsing from a string into a decimal, but System.Text.Json
does not. JSON.NET 支持将字符串解析为十进制,但System.Text.Json
不支持。 The easiest thing to do at this stage is to switch back to using JSON.NET, as described in the docs :在此阶段最简单的做法是切换回使用 JSON.NET,如文档中所述:
- Add a package reference to Microsoft.AspNetCore.Mvc.NewtonsoftJson .添加对Microsoft.AspNetCore.Mvc.NewtonsoftJson的包引用。
Update
Startup.ConfigureServices
to callAddNewtonsoftJson
.更新Startup.ConfigureServices
以调用AddNewtonsoftJson
。services.AddMvc() .AddNewtonsoftJson();
It would be more correct to pass the decimal as a JSON number, but it's clear that's not going to be an option for you.将小数作为 JSON 数字传递会更正确,但很明显这不会是您的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.