使用Validator.TryValidateProperty抛出ArgumentException问题排查
问题原因分析与解决方案
嘿,这个问题的根源一眼就能看出来——你调用Validator.TryValidateProperty的时候传错参数啦!
看你的ValidateProperty方法里这行关键代码:
bool valid = Validator.TryValidateProperty(property, context, results);
这里的property是方法传入的属性名称字符串(也就是"Listt"),但TryValidateProperty的第一个参数需要的是该属性的实际值(也就是你赋值给t.Listt的那个List<string>对象)。你把字符串传进去,系统自然会报错说类型不匹配,因为它期望的是List<string>类型,结果收到了string类型的属性名。
修正后的代码
你需要先通过反射获取目标属性的实际值,再传给验证方法,同时还要注意你原来的验证结果判断逻辑写反了!修改后的ValidateProperty方法如下:
public static JsonResult ValidateProperty(object obj, string property) { ValidationContext context = new ValidationContext(obj) { MemberName = property }; List<ValidationResult> results = new List<ValidationResult>(); // 新增:通过反射获取属性的实际值 var propertyInfo = obj.GetType().GetProperty(property); var propertyValue = propertyInfo?.GetValue(obj); bool valid = Validator.TryValidateProperty(propertyValue, context, results); // 修正判断逻辑:valid为true表示验证通过,无错误 if (valid) { return null; } string errors = ""; foreach (ValidationResult result in results) { errors += result.ErrorMessage + "\n <br>"; } Dictionary<string, string> err = new Dictionary<string, string>() { { "status", "fail" }, { "message", errors } }; return new JsonResult(err); }
这样修改后,再运行你的测试代码就不会抛出类型不匹配的异常了,验证逻辑也能正常工作。
内容的提问来源于stack exchange,提问作者Alireza Mn
相关产品推荐
相关产品推荐

