我正在迁移一个使用Newtonsoft的webapi(.NET8)。Json到System。文本Json。一切都很顺利,直到我偶然发现了一些与“必需”关键字有关的差异。
我将尝试使用WeatherForecast默认值来显示它。NET示例:
程序.cs
// code omitted for brevity
builder.Services.AddControllers();
// code omitted for brevity
天气预报.cs
public class WeatherForecast
{
public DateOnly Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
[Required]
public required string Summary { get; set; }
}
WeatherForecastController.cs
// code omitted for brevity
[HttpPost(Name = "WeatherForecast")]
public IActionResult Post(WeatherForecast request)
{
return Ok(request);
}
如果我调用Post端点而不在主体中传递Summary属性,则使用swagger,如下所示:
{
"date": "2024-01-01",
"temperatureC": 1,
}
我收到一个400,并显示以下错误消息:
"errors": {
"$": [
"JSON deserialization for type 'NewtonsoftVsSystemTextLab.WeatherForecast' was missing required properties, including the following: summary"
],
"request": [
"The request field is required."
]
},
另一方面,如果我使用Newtonsoft,只需将此扩展方法添加到Program.cs中的此行:
builder.Services.AddControllers().AddNewtonsoftJson();
我从DataAnnotations获得了用户友好的错误消息:
"errors": {
"Summary": [
"The Summary field is required."
]
},
有没有一种方法可以使用System获得相同的行为。文本Json不需要对源代码添加侵入性更改吗?