如果请求失败,我正在尝试在我的 WebApi 中实现详细描述的错误。当尝试将 json 主体绑定到 DTO 类时,对于模型绑定失败的第一个属性,我得到了非常好的可读错误,但随后它似乎停止了。我想返回模型绑定失败的所有字段的信息。
我的 DTO 类如下所示:
public class RequestDTO
{
public int FirstValue { get; set; }
public int SecondValue { get; set; }
}
传入以下JSON时
{
"firstValue": "y",
"secondValue": "x"
}
我得到以下回复
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|6ba7ef4a-442494fd16304f12.",
"errors": {
"$.firstValue": [
"The JSON value could not be converted to System.Int32. Path: $.firstValue | LineNumber: 1 | BytePositionInLine: 18."
]
}
}
我想要实现的是得到像
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|6ba7ef4a-442494fd16304f12.",
"errors": {
"$.firstValue": [
"The JSON value could not be converted to System.Int32. Path: $.firstValue | LineNumber: 1 | BytePositionInLine: 18."
],
"$.secondValue": [
"The JSON value could not be converted to System.Int32. Path: $.secondValue | LineNumber: 1 | BytePositionInLine: 19."
]
}
}
但我就是不知道该怎么做。我希望我的问题足够清楚,否则请发表评论,我会更新。
从 3.0 版 ASP.NET Core 开始System.Text.Json
用于处理 JSON。它在第一个错误时停止反序列化,并且似乎没有禁用它的设置。
如果您需要更多反序列化错误,您可以使用旧的Newtosoft.Json
. 只需添加Microsoft.AspNetCore.Mvc.NewtonsoftJson
nuget 包并添加更改以下行ConfigureServices
services.AddControllers();
到
services.AddControllers().AddNewtonsoftJson();
但是,System.Text.Json
已经获得了更好的性能,建议使用它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句