首页 > Web开发 > 详细

参数模型检验过滤器 NetCore版

时间:2021-01-13 14:46:36      阅读:38      评论:0      收藏:0      [点我收藏+]
    /// <summary>
    /// 参数模型检验过滤器 NetCore版
    /// </summary>
    public class ParaModelValidateAttribute : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            //本方法的所有参数描述符
            IList<ParameterDescriptor> actionParameters = filterContext.ActionDescriptor.Parameters;

            //只有这个方法需要参数的时候才进行校验
            if (actionParameters.Count != 0)
            {

                dynamic paraModel = filterContext.ActionArguments.FirstOrDefault().Value;

                ParaModelValidateHelper.Validate(paraModel);

            }

        }

    }

 

    public static class ParaModelValidateHelper
    {
        /// <summary>
        /// 参数模型校验
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static void Validate<T>(T entity) where T : class
        {
            Type type = entity.GetType();
            PropertyInfo[] properties = type.GetProperties();

            //循环模型的所有参数
            foreach (var item in properties)
            {

                //校验必填参数
                if (item.IsDefined(typeof(RequiredAttribute), true))//判断该参数是否有Required特性
                {

                    var value = item.GetValue(entity);//获取值
                    if (value == null || string.IsNullOrWhiteSpace(value.ToString()))
                    {

                        throw new Exception(string.Format("缺少必填参数{0}", item.Name));

                    }
                }

                //增加其他类型的校验的话接着写IF
                //System.ComponentModel.DataAnnotations


            }

        }
    }

 

参数模型检验过滤器 NetCore版

原文:https://www.cnblogs.com/solaxtube/p/14271628.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!