|
| 1 | +using System; |
| 2 | +using System.ComponentModel.DataAnnotations; |
| 3 | +using System.Linq; |
| 4 | +using System.Reflection; |
| 5 | +using WebApiClient.Contexts; |
| 6 | + |
| 7 | +namespace WebApiClient |
| 8 | +{ |
| 9 | + /// <summary> |
| 10 | + /// 提供参数值和参数的属性值输入合法性验证 |
| 11 | + /// </summary> |
| 12 | + static class ParameterValidator |
| 13 | + { |
| 14 | + /// <summary> |
| 15 | + /// 类型的属性否需要验证缓存 |
| 16 | + /// </summary> |
| 17 | + private static readonly ConcurrentCache<Type, bool> cache = new ConcurrentCache<Type, bool>(); |
| 18 | + |
| 19 | + /// <summary> |
| 20 | + /// 返回是否需要进行属性验证 |
| 21 | + /// </summary> |
| 22 | + /// <param name="instance">实例</param> |
| 23 | + /// <returns></returns> |
| 24 | + private static bool IsNeedValidateProperty(object instance) |
| 25 | + { |
| 26 | + if (instance == null) |
| 27 | + { |
| 28 | + return false; |
| 29 | + } |
| 30 | + |
| 31 | + var type = instance.GetType(); |
| 32 | + if (type == typeof(string) || type.GetTypeInfo().IsValueType == true) |
| 33 | + { |
| 34 | + return false; |
| 35 | + } |
| 36 | + |
| 37 | + return cache.GetOrAdd(type, t => t.GetProperties().Any(p => p.CanRead && p.IsDefined(typeof(ValidationAttribute), true))); |
| 38 | + } |
| 39 | + |
| 40 | + /// <summary> |
| 41 | + /// 验证参数值输入合法性 |
| 42 | + /// 验证参数的属性值输入合法性 |
| 43 | + /// </summary> |
| 44 | + /// <param name="parameter">参数描述</param> |
| 45 | + /// <exception cref="ValidationException"></exception> |
| 46 | + public static void Validate(ApiParameterDescriptor parameter) |
| 47 | + { |
| 48 | + var name = parameter.Name; |
| 49 | + var instance = parameter.Value; |
| 50 | + |
| 51 | + foreach (var validation in parameter.ValidationAttributes) |
| 52 | + { |
| 53 | + validation.Validate(instance, name); |
| 54 | + } |
| 55 | + |
| 56 | + if (IsNeedValidateProperty(instance) == true) |
| 57 | + { |
| 58 | + var ctx = new ValidationContext(instance) { MemberName = name }; |
| 59 | + Validator.ValidateObject(instance, ctx, true); |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments