从 .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 Core 后端应用程序.一切都很好,直到我决定从 ASP.NET Core 2.2 迁移到 3.0-preview-9.
I have an Angular front-end app and an ASP.NET Core back-end app. Everything was fine until I decided to migrate from ASP.NET Core 2.2 to 3.0-preview-9.
例如,我有一个 DTO 类:
For example, I have a DTO class:
public class DutyRateDto
{
public string Code { get; set; }
public string Name { get; set; }
public decimal Rate { get; set; }
}
以及一个 JSON 请求示例:
And an example JSON request:
{
"name":"F",
"code":"F",
"rate":"123"
}
在迁移之前,这是一个有效的请求,因为 123
被解析为十进制.但是现在,在迁移后,我收到此正文的 HTTP 400 错误:
Before migration, this was a valid request because 123
was parsed as a decimal. But now, after migration, I am getting an HTTP 400 error with this body:
{
"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.
如果我发送以下内容:
{
"name":"F",
"code":"F",
"rate":123
}
一切正常.但这意味着我需要更改到目前为止我写的每个请求.所有其他数据类型(int
、bool
、...)也是如此.
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
, …).
有谁知道我可以如何避免这种情况并在不更改我的请求的情况下使其正常工作?
Does anybody know how I can avoid this and make it work without changing my requests?
推荐答案
ASP.NET Core 3 使用 System.Text.Json
而不是 Newtonsoft.Json
(又名 JSON).NET) 来处理 JSON.JSON.NET 支持从字符串解析为十进制,但 System.Text.Json
不支持.如文档:
ASP.NET Core 3 uses System.Text.Json
instead of Newtonsoft.Json
(aka JSON.NET) for handling JSON. JSON.NET supports parsing from a string into a decimal, but System.Text.Json
does not. The easiest thing to do at this stage is to switch back to using JSON.NET, as described in the docs:
- 添加对 Microsoft.AspNetCore.Mvc.NewtonsoftJson 的包引用.
更新
Startup.ConfigureServices
以调用AddNewtonsoftJson
.
- Add a package reference to Microsoft.AspNetCore.Mvc.NewtonsoftJson.
Update
Startup.ConfigureServices
to callAddNewtonsoftJson
.
services.AddMvc()
.AddNewtonsoftJson();
将十进制数作为 JSON 数字传递会更正确,但很明显这不适合您.
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.
这篇关于从 .NET Core 2.2 迁移到 3.0-preview-9 后,模型绑定停止工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!