我有一个有趣的问题。我有一些模型,其中包含一些属性所需的数据注释。
public class Consumer : MongoEntity
{
public Consumer()
{
Products = new List<Product>();
}
[Required]
public string Email { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
[Required]
public Location CurrentLocation { get; set; }
public List<Product> Products { get; set; }
}
现在在我的web api控制器中,我接受这个作为参数,如下所示:
[Route("")]
[ValidateModel]
public IHttpActionResult Post([FromBody]Consumer consumer)
{
try
{
if (ModelState.IsValid)
{
_consumerService.Create(consumer);
return Ok("User created sucessfully.");
}
return BadRequest("User object is not complete. It's missing mandatory fields");
}
catch
{
return InternalServerError(new Exception("Something went wrong while saving the data back to database."));
}
}
我的印象是,如果消费者模型的任何必需字段为null,则模型状态应为false,但它始终返回true。当我向控制器发送空体时,Web api仅将模型状态设置为null。这有什么合理的解释吗?为什么web api不考虑复杂参数类型的必需属性?