通用的参数验证方法

public class CheckReuestHelper
    {
        /// <summary>
        /// 验证请求参数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        public static void CheckRequestParam<T>(T request) where T : class
        {
            if (request == null)
            {
                throw new KYException("参数不能为空");
            }
            PropertyInfo[] fields = typeof(T).GetProperties();
            var customerAttrFields = fields.Where(x => x.CustomAttributes.Any(t => t.AttributeType == typeof(RequestVildateAttribute))).ToList();
            if (!customerAttrFields.Any())
            {
                throw new Exception(string.Format("{0},验证模型中没有使用自定义特性RequestVildate", typeof(T).FullName));
            }
            foreach (var field in customerAttrFields)
            {
                var attr = field.GetCustomAttributes(typeof(RequestVildateAttribute), false).FirstOrDefault();
                if (attr == null) continue;
                var customerAttr = (RequestVildateAttribute)attr;
                if (customerAttr.IsNull && customerAttr.DefualtValue == null && customerAttr.Length == 0)
                {
                    continue;
                }
                if (customerAttr.IsNull && customerAttr.DefualtValue != null)
                {
                    field.SetValue(request, customerAttr.DefualtValue);
                    continue;
                }
                var val = field.GetValue(request, new object[] { });
                if (!customerAttr.IsNull && (val == null || (string)val == ""))
                {
                    throw new KYException(string.Format("{0},不能为空", customerAttr.FieldDesc));
                }
                if (!string.IsNullOrEmpty(customerAttr.Reg))
                {
                    Regex reg = new Regex(customerAttr.Reg);
                    if (!reg.IsMatch(val.ToString(), 0))
                    {
                        throw new KYException(string.Format("{0},数据格式不正确", customerAttr.FieldDesc));
                    }
                }
                if (customerAttr.Length > 0 && val != null)
                {
                    if (val.As<string>().Length > customerAttr.Length)
                    {
                        throw new KYException(string.Format("{0},字符长度不能超过{1}", customerAttr.FieldDesc, customerAttr.Length));
                    }
                }
                if (customerAttr.DataType == RequestDataType.Number)
                {
                    decimal outnumber = 0;
                    if (!decimal.TryParse(val.ToString(), out outnumber))
                    {
                        throw new KYException(string.Format("{0},只能是数字", customerAttr.FieldDesc));
                    }
                }
                else if (customerAttr.DataType == RequestDataType.DateTime)
                {
                    DateTime defualTime;
                    if (!DateTime.TryParse(val.ToString(), out defualTime))
                    {
                        throw new KYException(string.Format("{0},只能是日期", customerAttr.FieldDesc));
                    }
                }
                else if (customerAttr.DataType == RequestDataType.Boolean)
                {
                    bool bl;
                    if (!bool.TryParse(val.ToString(), out bl))
                    {
                        throw new KYException(string.Format("{0},只能是Bool类型", customerAttr.FieldDesc));
                    }
                }
            }
        }
    }

这里是检查类

 /// <summary>
    /// 通用验证请求参数特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class RequestVildateAttribute : System.Attribute
    {
        /// <summary>
        /// 是否可以为空
        /// </summary>
        private bool _isNull;

        /// <summary>
        /// 数据类型
        /// </summary>
        private RequestDataType _dataType;

        /// <summary>
        /// 默认值
        /// </summary>
        private object _defualtValue;

        /// <summary>
        /// 字段描述
        /// </summary>
        private string _fieldDesc;

        /// <summary>
        /// 正则表达式
        /// </summary>
        private string _reg;

        /// <summary>
        /// 长度
        /// </summary>
        private int _length;

        /// <summary>
        /// 是否可空
        /// </summary>
        public bool IsNull
        {
            get { return _isNull; }
        }

        /// <summary>
        /// 数据类型
        /// </summary>
        public RequestDataType DataType
        {
            get { return _dataType; }
        }

        /// <summary>
        /// 字段备注
        /// </summary>
        public string FieldDesc
        {
            get { return _fieldDesc; }
        }

        /// <summary>
        /// 默认值
        /// </summary>
        public object DefualtValue
        {
            get { return _defualtValue; }
        }

        /// <summary>
        /// 正则表达式
        /// </summary>
        public string Reg
        {
            get { return _reg; }
        }

        /// <summary>
        /// 字符长度
        /// </summary>
        public int Length
        {
            get { return _length; }
        }

        public RequestVildateAttribute(bool Is_Null, RequestDataType Requestdata_Type, string Field_Desc,int length=0, object Replace_Value=null,string Regex="")
        {
            _isNull = Is_Null;
            _dataType = Requestdata_Type;
            _defualtValue = Replace_Value;
            _fieldDesc = Field_Desc;
            _reg = Regex;
            _length = length;
        }
    }

    public enum RequestDataType
    {
        /// <summary>
        /// 字符串
        /// </summary>
        String = 0,

        /// <summary>
        /// 数字
        /// </summary>
        Number,

        /// <summary>
        /// 时间
        /// </summary>
        DateTime,

        /// <summary>
        /// bool类型
        /// </summary>
        Boolean
    }

这个是特性类

下面是使用

 public class InsertExpenseRequest
    {
        /// <summary>
        /// 手机号码
        /// </summary>
        [RequestVildate(false, RequestDataType.String, "手机号码",20)]
        public string MobilePhone { get; set; }

        /// <summary>
        /// 报销金额
        /// </summary>
        [RequestVildate(false, RequestDataType.Number, "报销金额",20)]
        public decimal Amount { get; set; }

        /// <summary>
        /// 报销分类
        /// </summary>
        [RequestVildate(false, RequestDataType.String, "报销分类",50)]
        public string ExpenseType { get; set; }

        /// <summary>
        /// 来源
        /// </summary>
        [RequestVildate(false, RequestDataType.String, "来源",50)]
        public string Source { get; set; }

        /// <summary>
        /// 备注
        /// </summary>
        [RequestVildate(true, RequestDataType.String, "备注", 200)]
        public string Remark { get; set; }
    }

这里是Model

调用如下

        /// <summary>
        /// 保存信息
        /// </summary>
        /// <returns></returns>
        public void SaveInfo(BankAndPhoneSaveRequest request)
        {
            CheckReuestHelper.CheckRequestParam(request);
            //业务代码
        }

做个笔记,留着以后备用,有需要的朋友可以直接拿过去用,也可以改进,做成拦截器的方式也可以

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值