作者:墨镜猛女班长 | 来源:互联网 | 2023-08-30 19:24
Ihavethiswebapiandtryingtousethemodelstate.IsValidfunction,butihaveranintosomestr
I have this webapi and trying to use the "modelstate.IsValid" function, but i have ran into some strange problem. I have the following method in my controller:
我有这个webapi并尝试使用“modelstate”。是有效的函数,但是我遇到了一些奇怪的问题。我的控制器有以下方法:
[HttpPut]
[Route("{id}")]
public async Task Put([FromBody]ItemUpdateModel model, [FromRoute]int id)
{
if (!ModelState.IsValid) //Here i have a breakpoint!
{
return BadRequest(new
{
code = 400,
message = ModelState.Values.First().Errors.First().ErrorMessage
});
}
}
And here is the model, ItemUpdateModel
这是模型ItemUpdateModel
using System.ComponentModel.DataAnnotations;
namespace TestApi.Models
{
public class ItemUpdateModel
{
[Required]
[Display(Name = "title")]
[MaxLength(40)]
public string Title { get; set; }
[Required]
[Display(Name = "discount")]
public double Discount { get; set; }
[Required]
[Display(Name = "priceupdate")]
public bool PriceUpdate { get; set; }
}
}
I use Postman to send this http-request in the body with verb PUT and format json:
我使用Postman将这个http请求以谓词PUT和格式json发送到主体:
{ "title": "Some test", "discount": 0, "priceupdate": false }
{"title": "Some test", "discount": 0, "priceupdate": false}
This request should pass ok, but even if i try to leave out some properties the modelstate is always true. So when looking into the modelstate, this model aint binding at all to it. Only the [FromRoute]int id is bind, and the modelstate gets valid.
这个请求应该传递ok,但即使我尝试省略一些属性,modelstate始终为true。因此,当研究模型状态时,这个模型对它没有约束力。只有[FromRoute]int id被绑定,模型状态才有效。
The model is anyway getting filled with data and working except from the modelstate validation/binding.
无论如何,除了模型状态验证/绑定之外,模型都在填充数据并工作。
Also in the header im including: "application/json; charset=utf-8"
在标题中还包括:“应用/json;charset = utf - 8”
Anyone can help me with this, i have struggled a lot with this that seems like a really simple task :)
任何人都可以帮助我做这件事,我一直在努力做这件事,这似乎是一项非常简单的任务:
Thanks!
谢谢!
1 个解决方案