NET 基于ValidationContext和反射,调用过滤器校验参数

业务背景:

页面可视化批量操作数据,支持添加修改删除等操作,某天耐不住客户拍脑袋,要求把该功能改成文件上传
文件流没办法使用之前的【过滤器校验参数】逻辑,重新写容易出毛病【主要是上头懒得折腾】,就想出了这个骚操作
PS1:以前流程为【浏览器选择文件 / 浏览器展示&操作数据 / 调用批量上传数据接口】
PS2:现在流程为【浏览器选择文件 / 调用上传接口】

1.添加引用[展开项目 / 选中“引用” / 右键 / 添加引用 / 程序集]:System.ComponentModel.DataAnnotations

2.校验核心代码

                var itemModel = dtoList[i];
                var context = new System.ComponentModel.DataAnnotationsValidationContext(itemModel);

                // 存在错误信息的字段集合
                var itemErrorFieldNameList = new List<string>();
                // 循环属性
                foreach (var itemMapping in mappingList)
                {
                    context.MemberName = itemMapping.RealName;
                    context.DisplayName = itemMapping.RealName;
                    var itemValue = entityType.GetProperty(itemMapping.RealName).GetValue(itemModel);
                    // 循环属性的特性
                    foreach (var itemObject in entityType.GetProperty(itemMapping.RealName).GetCustomAttributes(false))
                    {
                        ValidationAttribute validationAttribute = null;
                        if (itemObject is Filters.CustomRequiredAttribute)
                            validationAttribute = itemObject as Filters.CustomRequiredAttribute;
                        else if (itemObject is Filters.CustomNotSupportAttribute)
                            validationAttribute = itemObject as Filters.CustomNotSupportAttribute;
                        else if (itemObject is Filters.CustomRequiredDateAttribute)
                            validationAttribute = itemObject as Filters.CustomRequiredDateAttribute;
                        if (validationAttribute == null) continue;
                        var itemBoo = validationAttribute.GetValidationResult(itemValue, context);
                        if (itemBoo != null) itemErrorFieldNameList.Add(itemBoo.ErrorMessage);
                    }
                }
                if (!itemErrorFieldNameList.IsNullOrEmpty()) errorFieldNameList.Add($"第 {i + 2} 行字段【{itemErrorFieldNameList.Distinct().Join("/")}】的数据有问题!");

3.Mapping

4.CustomRequiredAttribute

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
    public class CustomRequiredAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var validPropertityDesc = validationContext.DisplayName;
            if (!value.IsValid())
            {
                return new ValidationResult(validPropertityDesc);
            }
            return ValidationResult.Success;
        }
    }

 

上一篇:eclipse debug模式


下一篇:神经网络人脸识别3笔记