升级.netcore版本后,Json主体无法动态地从字符串转换为int



升级前,.Netcore版本为2.2,JSON http请求体中的字符串可以在JSON 下面的对象中转换为int


Post: api/ValidateMember
Host: XXXX
Content-Type: application/json
{
"id": "125324"
}

到对象:

class RequestWithID
{
public int id {get;set;}
}
...
[HttpPost("api/ValidateMember")]
public bool ValidateMember(RequestWithID requestWithID)
{
...
}

这以前可以很好地工作。

但在Netcore版本升级到3.1之后。相同的请求总是会出现错误:JSON值无法转换为System.Int32。如何支持在.Netcore 3.1中动态解析字符串为int?

说明

从ASP.NET Core 3.0开始,默认情况下使用System.Text.Json序列化程序,而不是以前的Newtonsoft.Json.

尽管Newtonsoft.Json比System.Text.Json慢(链接1&链接2(,但它有更多的功能,因此有时会根据您的经验做出更合适的选择。

解决方案

为了恢复Newtonsoft.Json序列化程序,请将Microsoft.AspNetCore.Mvc.NewtonsoftJson包引用添加到您的项目中,并在Startup:中调用AddNewtonsoftJson()

public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddNewtonsoftJson();
}

此外,在添加自定义转换器时,请确保使用Newtonsoft.Json命名空间而不是System.Text.Json,因为两者都提供了名称相似的类型。

您可以使用JsonNumberHandlingAttribute,它可以在1行中正确处理所有内容,因此您可以继续使用System.Text.Json(比Newtonsoft.Json更快(

[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)]
public string Id { get; set; }
....

根据https://stackoverflow.com/a/59099589

最新更新