asp.net核心 - modelstate badrequest不一致的行为

时间:2017-01-10 06:25:36

标签: c# asp.net validation asp.net-core

我有一个简单的模型:

public class Item : Entity<int>
{
    [Required]
    public string Name { get; set; }
    [Required]
    public int Cost { get; set; }
}

内部控制器:

[HttpPost]
public async Task<IActionResult> Create([FromBody] Item item)
{
    if(!ModelState.IsValid) 
    {
       return BadRequest(ModelState);
    }
    repository.Create(item);
    await repository.SaveAsync();
    return Created($"/api/v1/items/{item.Id}", new { message = "Item was created successfully!" });
}

现在,为了跟踪三个不正确的样本输入,我得到以下回复:

样品#1:

POST http://localhost:5000/api/v1/items
content-type: application/json

{
    "name": "sample1",
    "cost": $100000
}

响应:

{
  "cost": [
    "The input was not valid."
  ]
}

样本#2:

POST http://localhost:5000/api/v1/items
content-type: application/json

{
    "name": "sample2",
    "cost": "10000000000000000000000000"
}

响应:

{
  "cost": [
    "The input was not valid."
  ]
}

示例#3:这个似乎是一个错误。出现一个空键(而不是int超出范围错误)

POST http://localhost:5000/api/v1/items
content-type: application/json

{
    "name": "sample3",
    "cost": 10000000000000000000000000
}

响应:

{
  "": [
    "The input was not valid."
  ],
  "cost": [
    "The input was not valid."
  ]
}

修改 在github上添加了跟踪票证 - https://github.com/aspnet/Mvc/issues/5672

1 个答案:

答案 0 :(得分:1)

第一个和最后一个是无效的json,第二个是整数cost的数字太高。确保您的费用不超过INT_MAX: 2147483647