如何让模型绑定在第一次失败后不停止



如果请求失败,我正在尝试在我的 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。只需添加 nuget 包Microsoft.AspNetCore.Mvc.NewtonsoftJson并在ConfigureServices中添加更改以下行

services.AddControllers();

services.AddControllers().AddNewtonsoftJson();

但是,System.Text.Json具有更好的性能,建议使用它。

最新更新