I've beenlookingaround我認爲我的解決方案很好,但不知何故ModelState.IsValid
屬性總是true
。ModelState始終被認爲是有效的,不管所需字段中的值是否爲空
考慮下面的代碼片段:
[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; }
}
仍然給我一個有效的ModelState,即使它清楚地表明,需要的屬性是null
。
我是什麼俯瞰?
Validator.ValidateObject(model, new ValidationContext(model));
在UpdateAddress
方法的頂部上Street
字段拋出一個ValidationException
所以它實際上可以驗證模型。問題依然存在:爲什麼不自動?
此外,this不適用,因爲我的model
不是null
。
的可能重複[測試的ModelState總是在asp.net mvc的有效(http://stackoverflow.com/questions/8165026/testing-modelstate-is-always-valid-in-asp-net- MVC) – 2014-11-05 17:22:10