ModelState is always considered valid, regardless of null values in required fields

爱⌒轻易说出口 提交于 2019-12-05 02:31:40
Jeroen Vannevel

Turns out that this answer had the right idea but the solution didn't quite fit.

Validation happens when the posted data is bound to the view model. The view model is then passed into the controller. You are skipping part 1 and passing a view model straight into a controller.

Which is correct, but the proposed solution throws a ValidationException instead of simply setting the IsValid property to false.

Luckily, there is a specific method that can do this: ApiController.Validate(). By adding these lines to my Unit Test it sets the ModelState to invalid and does not throw an exception.

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

Nothing in your execution path causes validation to occur. That's done as part of the model binding, which you aren't doing as you're manually creating your model instance.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!