问题描述
我有一个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.
但是,如果我发送以下内容:
If I send the following, however:
{
"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
(aka 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:
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后,模型绑定停止工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!