【问题标题】:Json.Net returns two errors when a value is incorrect format当值格式不正确时,Json.Net 返回两个错误
【发布时间】: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


【解决方案1】:

您提供的 JSON 值无效,属性 Age 需要一个数字,JSON 对象应类似于:

{
    "Age": 22
}

对于 JSON,属性值可以是字符串(带单引号或双引号)、数字(不带引号)、true 或 false、null、对象或数组。

【讨论】:

  • 嗨,我知道它无效。我的问题是为什么它会返回两个错误? “在 JSON 中找不到必需的属性‘年龄’。路径‘’,第 3 行,位置 1。”提供年龄时不正确(尽管它是无效值。
  • 试图重现该问题,我得到的唯一错误与属性的类型有关:“无法将 JSON 值转换为 System.Nullable`1[System.Int32]。路径: $.age | LineNumber: 1 | BytePositionInLine: 14。"
  • 嗨,阿赫德迪尔。是通过网络 API 吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-28
  • 2021-09-27
  • 1970-01-01
相关资源
最近更新 更多