簡體   English   中英

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

[英]asp.net core - modelstate badrequest inconsistent behaviour

我有一個簡單的模型:

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

第一個和最后一個是無效的json,第二個是對於整數cost而言過高的數字。 確保您的費用不超過INT_MAX: 2147483647

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM