예제 #1
0
        /// <summary>
        /// InputDto属性验证
        /// </summary>
        public static void Validate <TKey>(this IInputDto <TKey> dto)
        {
            Check.NotNull(dto, nameof(dto));
            Type type = dto.GetType();

            if (!_dict.TryGetValue(type, out ConcurrentDictionary <PropertyInfo, ValidationAttribute[]> dict))
            {
                PropertyInfo[] properties = type.GetProperties();
                dict = new ConcurrentDictionary <PropertyInfo, ValidationAttribute[]>();
                if (properties.Length == 0)
                {
                    _dict[type] = dict;
                    return;
                }
                foreach (var property in properties)
                {
                    dict[property] = null;
                }
                _dict[type] = dict;
            }

            foreach (PropertyInfo property in dict.Keys)
            {
                if (!dict.TryGetValue(property, out ValidationAttribute[] attributes) || attributes == null)
        /// <summary>
        /// 检查数据传输对象是否合法,不合法时返回错误消息
        /// </summary>
        public static bool IsValid(this IInputDto inputDto, out IList <string> errors)
        {
            errors = new List <string>();
            var properties = inputDto.GetType().FastGetProperties();

            foreach (var property in properties)
            {
                if (!property.CanRead)
                {
                    continue;
                }
                var attributes = property.FastGetCustomAttributes(typeof(ValidationAttribute));
                if (attributes.Length == 0)
                {
                    continue;
                }
                var value = property.FastGetValue(inputDto);
                // 获取属性名称
                var propertyName = new T(property
                                         .FastGetCustomAttributes(typeof(DescriptionAttribute))
                                         .OfType <DescriptionAttribute>()
                                         .FirstOrDefault()?.Description ?? property.Name).ToString();
                // 检查标记在属性上的验证属性
                foreach (var attribute in attributes.OfType <ValidationAttribute>())
                {
                    if (attribute.IsValid(value))
                    {
                        continue;
                    }
                    errors.Add((string)FormatValidationErrorMethod
                               .MakeGenericMethod(attribute.GetType())
                               .FastInvoke(null, attribute, propertyName));
                }
            }
            return(errors.Count == 0);
        }