dotnet验证参数

组长提了一个需求,前端传递过来参数的时候,我们要验证一下参数是否都传递过来了,所以我专门写了一个验证工具类,调用就好了。

第一个参数为 前端传递到Controller封装的实体类,第二个参数为这个实体类中哪些参数是必须要验证的,用list封装。

我把需要验证的参数统一写到了一个配置类,类似如下格式:

1   public const string COURSE_ADD_PARAM = "courseName;auditor;author;" +
2             "courseDuration;teachingMethodId;courseUserId;courseLink;effectiveTime;" +
3             "expiryTime;coursePurpose;chapterCode;skillLevel";

然后根据;分割,拿到list传递给下述方法就好了。

 1   /*
 2          * @Description:验真参数中指定的属性是否为空
 3          * 如果只要有任意指定的参数属性为空 返回false
 4          * 如果全部指定的参数属性不为空 返回true
 5          * @Param T t,List<string> list
 6          */
 7         public static Boolean VerificationParam<T>(T t,List<string> list)
 8         {
 9           
10             if (t == null)
11             {
12                 return false;
13             }
14             System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
15 
16             if (properties.Length <= 0)
17             {
18                 return false;
19             }
20 
21             foreach (System.Reflection.PropertyInfo item in properties)
22             {
23                 string name = item.Name;
24                 object value = item.GetValue(t, null);
25                 if (value == null && list.Contains(name))
26                 {
27                     return false;
28                 }
29                
30             }
31            
32             return true;
33         }

猜你喜欢

转载自www.cnblogs.com/battlecry/p/11359240.html
今日推荐