无论必需字段中的空值如何,ModelState始终被视为有效

时间:2014-11-05 16:25:53

标签: c# asp.net asp.net-web-api asp.net-web-api2 modelstate

I've been looking around我认为我的解决方案很好,但ModelState.IsValid属性总是true

请考虑以下代码段:

[Route("address")]
[HttpPut]
[ResponseType(typeof(UserViewModel))]
public IHttpActionResult UpdateAddress([FromBody] UpdateAdressValidationModel model)
{
   if (!ModelState.IsValid)
   {
       return BadRequest(ModelState);
   }
   // irrelevant code omitted
}

[TestMethod]
public void UpdateAddress_WithoutStreet_ReturnsHttpCode400()
{
    var userController = new UserController(new UserRepository(_context));
    var addressInfo = new UpdateAdressValidationModel
    {
        City = "Ghent",
    };

    var response = userController.UpdateAddress(addressInfo) as BadRequestResult;

    Assert.IsNotNull(response);
}

public class UpdateAdressValidationModel
{
    [Required]
    public string Street { get; set; }

    [Required]
    public int? Number { get; set; }

    [Required]
    public string Bus { get; set; }

    [Required]
    public int? PostalCode { get; set; }

    [Required]
    public string City { get; set; }
}

仍然给我一个有效的模型状态,即使它清楚地表明所需的属性是null

enter image description here

我在俯瞰什么?

请注意manually adding

Validator.ValidateObject(model, new ValidationContext(model));
UpdateAddress方法顶部的

会在ValidationException字段上抛出Street,因此它实际上可以验证模型。问题仍然存在:为什么不自动?

此外,this不适用,因为我的model不是null

2 个答案:

答案 0 :(得分:7)

事实证明this answer有正确的想法,但解决方案并不合适。

  

当发布的数据绑定到视图模型时,将进行验证。然后将视图模型传递到控制器中。您正在跳过第1部分并将视图模型直接传递给控制器​​。

哪个是正确的,但建议的解决方案会抛出ValidationException,而不是简单地将IsValid属性设置为false

幸运的是,有一种特定方法可以做到这一点:ApiController.Validate()。通过将这些行添加到我的单元测试中,它会将ModelState设置为无效,不会抛出异常

userController.Configuration = new HttpConfiguration();
userController.Validate(addressInfo);

答案 1 :(得分:0)

执行路径中没有任何内容会导致验证发生。这是作为模型绑定的一部分完成的,当您手动创建模型实例时,您没有这样做。