1. 程式人生 > 其它 >NET 基於ValidationContext和反射,呼叫過濾器校驗引數

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;
        }
    }