• 封装统一数据验证方法


    在验证api数据格式或者完整性时,每个接口单独写验证范式比较麻烦。这里在。netcore环境下封装了一个验证工具类

       public class Validate
        {
            /// <summary>
            /// 封装统一数据验证方法
            /// </summary>
            /// <typeparam name="T">DTOModel</typeparam>
            /// <param name="t">需要验证的数据对象</param>
            /// <returns></returns>
            public static ValidateResult ValidataData<T>(T t) where T : class
            {
                ValidateResult result = new ValidateResult() { Flag = true };
                if (t == null)
                {
                    result.Flag = false;
                    result.ErrorMessage = "没有输入的数据";
                    return result;
                } 
                foreach (var property in t.GetType().GetProperties())
                {
                    if (property.IsDefined(typeof(BaseValidateAttribute), true))
                    {
                        foreach (var attr in property.GetCustomAttributes(typeof(BaseValidateAttribute), true))
                        {
                            var value = property.GetValue(t);
                            if ((attr.GetType().Name != "RequiredAttribute") && (value == null || string.IsNullOrEmpty(value.ToString())))
                            {
                                continue;
                            }
                            var validate = attr as BaseValidateAttribute;
                            if (validate!=null)
                            {                            
                                var flag = validate.ValidateAction(value, property); // 执行验证
                                if (!flag)
                                {
                                    // 验证不通过
                                    result.Flag = false;
                                    result.ErrorMessage = property.Name+validate.ErrorMessage;
                                    return result;                                
                                }
                            }
                        }
                    }
                }
                return result;
            }
    
    
        }
        /// <summary>
        /// 通用返回验证结果对象
        /// </summary>
        public class ValidateResult
        {
            /// <summary>
            /// 验证是否通过,true:通过,false:不通过
            /// </summary>
            public bool Flag { get; set; }
    
            /// <summary>
            /// 错误提示
            /// </summary>
            public string ErrorMessage { get; set; }
        }

    数据验证特性基类

        /// <summary>
        /// 数据验证特性基类
        /// </summary>
        public abstract class BaseValidateAttribute : Attribute
        {
            /// <summary>
            /// 错误提示
            /// </summary>
            public string ErrorMessage { get; set; }
    
    
            /// <summary>
            /// 执行验证
            /// </summary>
            /// <param name="value">属性值</param>
            /// <param name="obj">对应的属性对象</param>
            /// <returns></returns>
            public abstract bool ValidateAction(object value, PropertyInfo property);
    
    
        }

    自定义验证类根据业务场景需要自定义 举例:

        /// <summary>
        /// 验证字段非空
        /// </summary>
        public class RequiredAttribute : BaseValidateAttribute
        {
            public override bool ValidateAction(object value,PropertyInfo property)
            {
                if (value != null && !string.IsNullOrEmpty(value.ToString()))
                {
                    return true;
                }
                if (string.IsNullOrEmpty(this.ErrorMessage))
                {
                    this.ErrorMessage = $"字段不能为空";
                }
                return false;
            }
        }

    调用代码案例

      //验证参数
                context.ActionArguments.ForEach(f =>
                {
                    //通过反射获取对象的实例
                    var assembly = Assembly.Load("Enterprise_Credit.Model");
                    string typename = f.Value.ToString().Split(new char[] { '[', ']' })[1].ToString();
                    dynamic obj = assembly.CreateInstance(typename, true);
                    //将json转换为JToken
                    JToken jObj = JToken.Parse(JsonConvert.SerializeObject(f.Value));
                    if (jObj["Parameter"].HasValues)
                    {
                        //将传入的json参数映射到对象实例上
                        dynamic ocbj = JsonConvert.DeserializeAnonymousType(jObj["Parameter"].ToString(), obj);
                        //验证数据对象
                        ValidateResult result = Validate.ValidataData(ocbj);
                        if (!result.Flag)
                        {
                            context.Result = new ObjectResult(new Response<object>(ResultTypeEnum.ParamException, result.ErrorMessage));
                        }
                    }
                    else
                    {
                        context.Result = new ObjectResult(new Response<object>(ResultTypeEnum.ParamException, "没有传递参数."));
                    }
    
                });

    传入参数对象格式:

     /// <summary>
        /// 输入参数基类,所有输入参数命名规则是方法名+Input
        /// </summary>
        public class BaseInput<T> where T : class
        { 
            public T Parameter { get; set; }
            public Page Paging { get; set; }
            /// <summary>
            /// 人员编号
            /// </summary>
            [Required]
            public string UserCode { get; set; }
            public BaseInput(T t)
            {
                Parameter = t;
            }
            public BaseInput()
            {
                Parameter = new NoInputItem() as T;
            }
        }
        public class NoInputItem
        {
        }
        public class Page
        {
            /// <summary>
            /// 当前页码
            /// </summary>
            public int pageIndex { get; set; }
            /// <summary>
            /// 每页条数
            /// </summary>
            public int pageSize { get; set; }
        }

    传出对象数据格式

      public class ResponseBase
        {
            /// <summary>
            /// 接口消息返回状态类型
            /// </summary>
            public ResultTypeEnum ResultType { get; set; }
            /// <summary>
            /// 提示信息
            /// </summary>
            public string Message { get; set; }
        }
        /// <summary>
        /// 接口返回参数基类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public class Response<T> : ResponseBase
        {
            /// <summary>
            /// 具体数据内容
            /// </summary>
            public T Data { get; set; }
    
            public Response()
            {
                this.Data = default(T);
                this.ResultType = ResultTypeEnum.Success;
            }
    
            public Response(T data)
            {
                this.ResultType = ResultTypeEnum.Success;
                this.Data = data;
            }
    
    
            public Response(T data, string strMsg)
            {
                this.ResultType = ResultTypeEnum.Success;
                this.Data = data;
                this.Message = strMsg;
            }
    
            public Response(ResultTypeEnum resultType, string message)
            {
                ResultType = resultType;
                Message = message;
            }
    
        }
  • 相关阅读:
    Oracle之数据库的增删改查和格式的修改
    Oracle之表的相关操作
    Oracle之现有表上建新表、操作符、字符函数
    Oracle之用户和表空间
    相关Linux命令
    克隆环境
    机器学习笔记(四)神经网络的基本概念
    机器学习作业(二)逻辑回归——Python(numpy)实现
    机器学习作业(二)逻辑回归——Matlab实现
    机器学习笔记(三)逻辑回归
  • 原文地址:https://www.cnblogs.com/zzlblog/p/10837980.html
Copyright © 2020-2023  润新知