当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET MVC后台参数验证的几种方式

ASP.NET MVC后台参数验证的几种方式

2017年12月12日  | 移动技术网IT编程  | 我要评论

水陆突击队,暮光之城破晓下下载,中日开战 中方必败

前言

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

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

[httppost]
public actionresult register(registerinfo info)

一、通过 if-if 判断  

if(string.isnullorempty(info.username))

{

  return failjson("用户名不能为空");

}

if(string.isnullorempty(info.password))

{

  return failjson("用户密码不能为空")

} 

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

二、通过 dataannotation

mvc提供了dataannotation对action的model进行验证,说到底dataannotation就是一系列继承了validationattribute的特性,例如rangeattribute,requiredattribute等等。validationattribute 的虚方法isvalid 就是用来判断被标记的对象是否符合当前规则。asp.net mvc在进行model binding的时候,会通过反射,获取标记的validationattribute,然后调用 isvalid 来判断当前参数是否符合规则,如果验证不通过,还会收集错误信息,这也是为什么我们可以在action里通过modelstate.isvalid判断model验证是否通过,通过modelstate来获取验证失败信息的原因。例如上面的例子:

public class registerinfo

{

  [required(errormessage="用户名不能为空")]

  public string username{get;set;}

 [required(errormessage="密码不能为空")]

  public string password { get; set; }

} 

事实上在webform上也可以参照mvc的实现原理实现这个过程。这种方式的优点的实现起来非常优雅,而且灵活,如果有多个action共用一个model参数的话,只要在一个地方写就够了,关键是它让我们的代码看起来非常简洁。

不过这种方式也有缺点,通常我们的项目可能会有很多的接口,比如几十个接口,有些接口只有两三个参数,为每个接口定义一个类包装参数有点奢侈,而且实际上为这个类命名也是非常头疼的一件事。

三、dataannotation 也可以标记在参数上

通过验证特性的attributeusage可以看到,它不只可以标记在属性和字段上,也可以标记在参数上。也就是说,我们也可以这样写:

public actionresult register([required(errormessage="用户名不能为空")]string username, [required(errormessage="密码不能为空")]string password) 

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

四、自定义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可以权衡选择使用,这里我们可以扩展更多有用的信息,如错误描述等等。

总结

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网