aps.net手写验证模型的方法
/// <summary> /// 基础验证类 /// </summary> public class BaseValidator { /// <summary> /// 验证输入参数 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="requestModel"></param> /// <returns></returns> public static ResponseModel BaseCheckParamModel<T>(T requestModel) where T : class { var context = new System.ComponentModel.DataAnnotations.ValidationContext(requestModel, null, null); var errors = new List<System.ComponentModel.DataAnnotations.ValidationResult>(); //通用校验参数 var result = System.ComponentModel.DataAnnotations.Validator.TryValidateObject(requestModel, context, errors, true); if (!result) { return new ResponseModel(false, 1, errors.First().ErrorMessage); } return new ResponseModel(true, 0, "success"); } }
但是有个问题,那就是,如果验证的对象的某个属性是对象,那么这个子对象验证不到。