简体   繁体   中英

asp.net core - modelstate badrequest inconsistent behaviour

I have a simple model:

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

Inside controller:

[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!" });
}

Now, for following three incorrect sample inputs I get following responses:

Sample #1:

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

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

Response:

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

Sample #2:

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

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

Response:

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

Sample #3: This one seems like a bug. An empty key appears (instead of int out of range error)

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

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

Response:

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

Edit: Added a tracking ticket on github - https://github.com/aspnet/Mvc/issues/5672

First and last are invalid json and the second one has too high number for the integer cost . Make sure your cost does not exceed INT_MAX: 2147483647 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM