后台参数验证的几种方式

前言前端

  参数验证是一个常见的问题,不管是前端仍是后台,都需对用户输入进行验证,以此来保证系统数据的正确性。对于web来讲,有些人可能理所固然的想在前端验证就好了,但这样是很是错误的作法,前端代码对于用户来讲是透明的,稍微有点技术的人就能够绕过这个验证,直接提交数据到后台。不管是前端网页提交的接口,仍是提供给外部的接口,参数验证随处可见,也是必不可少的。总之,一切用户的输入都是不可信的。web

  参数验证有许多种方式进行,下面以mvc为例,列举几种常见的验证方式,假设有一个用户注册方法mvc

  [HttpPost]
  public ActionResult Register(RegisterInfo info)asp.net

1、经过 if-if 判断  ide

            if(string.IsNullOrEmpty(info.UserName))
            {
                return FailJson("用户名不能为空");
            }
            if(string.IsNullOrEmpty(info.Password))
            {
                return FailJson("用户密码不能为空")
            }

  逐个对参数进行验证,这种方式最粗暴,但当时在WebForm下也确实这么用过。对于参数少的方法还好,若是参数一多,就要写n多的if-if,至关繁琐,更重要的是这部分判断无法重用,另外一个方法又是这样判断。ui

2、经过 DataAnnotationspa

  mvc提供了DataAnnotation对Action的Model进行验证,说到底DataAnnotation就是一系列继承了ValidationAttribute的特性,例如RangeAttribute,RequiredAttribute等等。ValidationAttribute 的虚方法IsValid 就是用来判断被标记的对象是否符合当前规则。asp.net mvc在进行model binding的时候,会经过反射,获取标记的ValidationAttribute,而后调用 IsValid 来判断当前参数是否符合规则,若是验证不经过,还会收集错误信息,这也是为何咱们能够在Action里经过ModelState.IsValid判断Model验证是否经过,经过ModelState来获取验证失败信息的缘由。例如上面的例子:.net

    public class RegisterInfo
    {
        [Required(ErrorMessage="用户名不能为空")]
        public string UserName{get;set;}

        [Required(ErrorMessage="密码不能为空")]
        public string Password { get; set; }
    }

  事实上在webform上也能够参照mvc的实现原理实现这个过程。这种方式的优势的实现起来很是优雅,并且灵活,若是有多个Action共用一个Model参数的话,只要在一个地方写就够了,关键是它让咱们的代码看起来很是简洁。orm

  不过这种方式也有缺点,一般咱们的项目可能会有不少的接口,好比几十个接口,有些接口只有两三个参数,为每一个接口定义一个类包装参数有点奢侈,并且实际上为这个类命名也是很是头疼的一件事。对象

3、DataAnnotation 也能够标记在参数上

  经过验证特性的AttributeUsage能够看到,它不仅能够标记在属性和字段上,也能够标记在参数上。也就是说,咱们也能够这样写:

public ActionResult Register([Required(ErrorMessage="用户名不能为空")]string userName, [Required(ErrorMessage="密码不能为空")]string password)

  这样写也是ok的,不过很明显,这样写很方法参数会难看,特别是在有多个参数,或者参数有多种验证规则的时候。

4、自定义ValidateAttribute

  咱们知道能够利用过滤器在mvc的Action执行前作一些处理,例如身份验证,受权处理的。同理,这里也能够用来对参数进行验证。FilterAttribute是一个常见的过滤器,它容许咱们在Action执行先后作一些操做,这里咱们要作的就是在Action前验证参数,若是验证不经过,就再也不执行下去了。

  定义一个BaseValidateAttribute基类以下:

    public class BaseValidateAttribute : FilterAttribute
    {
        protected virtual void HandleError(ActionExecutingContext context)
        {
            for (int i = ValidateHandlerProviders.Handlers.Count; i > 0; i--)
            {
                ValidateHandlerProviders.Handlers[i - 1].Handle(context);
                if (context.Result != null)
                {
                    break;
                }
            }
        }
    }

  HandleError 用于在验证失败时处理结果,这里ValidateHandlerProviders提过IValidateHandler用于处理结果,它能够在外部进行注册。IValidateHandler定义以下:

    public interface IValidateHandler
    {
        void Handle(ActionExecutingContext context);
    }

  ValidateHandlerProviders定义以下,它有一个默认的处理器。

    public class ValidateHandlerProviders
    {
        public static List<IValidateHandler> Handlers { get; private set; }

        static ValidateHandlerProviders()
        {
            Handlers = new List<IValidateHandler>()
            {
                new DefaultValidateHandler()
            };
        }

        public static void Register(IValidateHandler handler)
        {
            Handlers.Add(handler);
        }
    }  

  这样作的目的是,因为咱们可能有不少具体的ValidateAttribute,能够把这模块独立开来,而把最终的处理过程交给外部决定,例如咱们在项目中能够定义一个处理器:

    public class StanderValidateHandler : IValidateHandler
    {
        public void Handle(ActionExecutingContext filterContext)
        {
            filterContext.Result = new StanderJsonResult()
            {
                Result = FastStatnderResult.Fail("参数验证失败", 555)
            };
        }
    }

  而后再应用程序启动时注册:ValidateHandlerProviders.Handlers.Add(new StanderValidateHandler());

  举个两个栗子:

  ValidateNullttribute:

    public class ValidateNullAttribute : BaseValidateAttribute, IActionFilter
    {
        public bool ValidateEmpty { get; set; }

        public string Parameter { get; set; }

        public ValidateNullAttribute(string parameter, bool validateEmpty = false)
        {
            ValidateEmpty = validateEmpty;
            Parameter = parameter;
        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string[] validates = Parameter.Split(',');
            foreach (var p in validates)
            {
                string value = filterContext.HttpContext.Request[p];
                if(ValidateEmpty)
                {
                    if (string.IsNullOrEmpty(value))
                    {
                        base.HandleError(filterContext);
                    }
                }
                else
                {
                    if (value == null)
                    {
                        base.HandleError(filterContext);
                    }
                }
            }
        }

        public void OnActionExecuted(ActionExecutedContext filterContext)
        {

        }
    }

  ValidateRegexAttribute:

    public class ValidateRegexAttribute : BaseValidateAttribute, IActionFilter
    {
        private Regex _regex;

        public string Pattern { get; set; }

        public string Parameter { get; set; }

        public ValidateRegexAttribute(string parameter, string pattern)
        {
            _regex = new Regex(pattern);
            Parameter = parameter;
        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string[] validates = Parameter.Split(',');
            foreach (var p in validates)
            {
                string value = filterContext.HttpContext.Request[p];
                if (!_regex.IsMatch(value))
                {
                    base.HandleError(filterContext);
                }
            }
        }

        public void OnActionExecuted(ActionExecutedContext filterContext)
        {

        }
    }

  更多的验证同理实现便可。

  这样,咱们上面的写法就变成:

        [ValidateNull("userName,password")]
        public ActionResult Register(string userName, string password)

  综合看起来,仍是ok的,与上面的DataAnnotation能够权衡选择使用,这里咱们能够扩展更多有用的信息,如错误描述等等。

总结

  固然每种方式都有有缺点,这个是视具体状况选择了。通常参数太多建议就用一个对象包装了。

相关文章
相关标签/搜索