【发布时间】:2020-03-18 16:59:20
【问题描述】:
我创建了一个非常简单的 web api,它有一个模型类如下:
public class Person
{
[JsonRequired]
public int? Age { get; set; }
}
还有一个控制器消息如下:
[HttpPost]
public void Post([FromBody] Person person)
{
}
当我使用以下 json 请求调用它时:
{
"age": "a"
}
我明白了:
{
"errors": {
"": [
"Required property 'age' not found in JSON. Path '', line 3, position 1."
],
"age": [
"Could not convert string to integer: a. Path 'age', line 2, position 11."
]
},
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "80000007-0003-ff00-b63f-84710c7967bb"
}
我不明白为什么我会在这里得到两个错误值,尤其是其中一个显然是不真实的......有什么想法吗?我不想更改为 [Required],因为您丢失了解释错误发生在哪个行号的漂亮错误。
谢谢
【问题讨论】:
-
发生这种情况是因为 1) 服务器收集所有错误并在反序列化完成后将它们返回给您,使用 Json.NET 的error handling mechanism; 2)从概念上讲,这里实际上有两个错误:i。
"a"无法反序列化为 int; ii.从未设置所需的属性Age。但是,错误消息具有误导性,如果它说"Required property 'age' not set from the JSON.事情可能会更清楚。
标签: json.net asp.net-web-api2 asp.net-core-2.0