我有一个一般看起来像的方法
public IActionResult SomeAction(Guid id, [FromBody] Request request)
{
//bunch of other stuff left out
AnotherObject obj = Mapper.Map(request);
if (ModelState.IsValid) {//only validation errors on the request object are found
//obj validation errors are ignored
}
}
在 Request 类中,我使用 DataAnnotations 来测试模型状态,它们工作正常。但是,在 AnotherObject 内部我也在使用 DataAnnotations,当我在此函数中测试 ModelState 时,.NET 会看到来自 Request 对象的验证错误,但不会出现在映射对象中。
此端点的调用者不知道 AnotherObject,也不需要知道。有没有办法让 .NET 尊重在 Controller 操作内部创建但未传入的对象的验证?
请您参考如下方法:
您可以使用 Validator手动测试对象的对象:
var obj = Mapper.Map(request);
var context = new ValidationContext(obj, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(obj, context, results);
参见 this short tutorial获取更多信息。
注意这不是递归的,根据AnotherObject的复杂度,你可能需要自己使用Reflection来递归遍历对象。
