值格式错误时,Json.Net返回两个错误

我创建了一个非常简单的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],因为您丢失了解释错误发生在哪个行号上的漂亮错误。

谢谢

lxleesjs 回答:值格式错误时,Json.Net返回两个错误

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

{
    "Age": 22
}

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

本文链接:https://www.f2er.com/3049833.html

大家都在问