参数校验特性的改进(全局注册及跳过校验)

前言

改进一下ParaModelValidateAttribute(参数校验)
1.在StartUp中对参数校验特性进行全局配置
2.添加一个跳过校验特性
3.修改ParaModelValidateAttribute
4.在需要跳过校验的方法上添加跳过校验特性

代码实现

在StartUp中对参数校验特性进行全局配置

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddControllersWithViews().AddNewtonsoftJson();

            #region 配置过滤器
            services.AddControllersWithViews(options => {
                options.Filters.Add(typeof(ErrorCatchAttribute));
            });
            services.AddControllersWithViews(options => {
                options.Filters.Add(typeof(ParaModelValidateAttribute));
            });
            #endregion

        }

添加一个跳过校验特性

    /// <summary>
    /// 忽略参数校验特性
    /// </summary>
    public class ParaModelValidateIgnoreAttribute : Attribute
    {

    }

修改ParaModelValidateAttribute

添加一段代码,如果方法有忽略参数校验的特性,则该方法不进行校验

    /// <summary>
    /// 参数模型检验过滤器 NetCore版
    /// </summary>
    public class ParaModelValidateAttribute : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext context)
        {

            //如果有忽略参数校验的特性 则不进行校验
            if (context.ActionDescriptor.EndpointMetadata.Any(item => item is ParaModelValidateIgnoreAttribute))
            {
                return;
            }

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

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

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

                ParaModelValidateHelper.Validate(paraModel);

            }
        }
    }

在需要跳过校验的方法上添加跳过校验特性

这样即使全局配置了参数校验,Login方法也会跳过校验

        [ParaModelValidateIgnore]
        public ActionResult Login(DemoParaModel paraModel)
        {
                
        }
posted @ 2021-01-26 13:38  sorachannel  阅读(171)  评论(0)    收藏  举报