在开发过程中,有时候会对用户输入进行过滤,以便保证平台的安全性。屏蔽的方法有很多种,但是今天我说的这种主要是利用MVC中的ActionFilterAttribute属性来实现。由于MVC天然支持AOP,所以我们这种过滤方式正好利用了MVC的这种特性。

下面请看步骤:

首先,当用户输入自己的名称的时候,带有类似<BR>的内容的时候,由于MVC默认是需要验证内容的,所以,会抛出一张黄页错误,提示用户:从客户端检测到潜在风险的Request值。这种页面是极为不友好的,同时也是我们作为开发最不想见到的页面,屏蔽这个错误很简单,就是在响应的页面ActionResult上面加上[ValidateInput(false)]的特性,这样当用户提交的时候,页面将不会再次对输入内容做检测。

如果容忍这样的行为,将会对系统的安全性造成威胁,所以最好的解决方法就是讲其中类似 <>等进行转义。

下面我们就来利用ActionFilterAttribute构造自己的转义过滤类:

   1:  using System.Web.Mvc;
   2:  using TinyFrame.Plugin.StrongTyped.Models;
   3:   
   4:  namespace TinyFrame.Plugin.StrongTyped
   5:  {
   6:      public class FilterCharsAttribute : ActionFilterAttribute
   7:      {
   8:          protected string parameterName = "t";
   9:          protected TestModel model;
  10:   
  11:          public override void OnActionExecuting(ActionExecutingContext filterContext)
  12:          {
  13:              base.OnActionExecuting(filterContext);
  14:   
  15:              //No Parameters, will return directly.
  16:              if (!filterContext.ActionParameters.ContainsKey(parameterName))
  17:                  return;
  18:   
  19:              var t = filterContext.ActionParameters[parameterName] as TestModel;
  20:   
  21:              //No Entity data, will return directly
  22:              if (t == null)
  23:                  return;
  24:   
  25:              //Replace chars that should be filtered
  26:              if (!string.IsNullOrEmpty(t.TName))
  27:                  t.TName = t.TName.Replace("<", "&lt").Replace(">", "&gt");
  28:              if (!string.IsNullOrEmpty(t.TSite))
  29:                  t.TSite = t.TSite.Replace("<", "&lt").Replace(">", "&gt");
  30:          }
  31:      }
  32:  }

第8行,代表我们的用户输入的实体类参数,具体的Controller代码如下:

   1:    public ActionResult Index(TestModel t)
   2:          {
   3:              ViewData["ConvertedModel"] = t;
   4:              return View();
   5:          }

第11行,通过重载OnActionExecuting方法,我们可以定义自己的Filter。

第19行,将获取的Input结果转换成entity。

第27,29行,将潜在的危险字符进行转义。

这样书写完毕之后,我们就打造了一个可以过滤掉关键字的Filter了。如果想要做的通用的话,需要对输入的filterContext.ActionParameters进行遍历,并通过反射构建实例,再通过反射字段值,实现通用的关键字过滤。这里我只提供思路,具体的做法就看自己了。

然后将这个方法加入到Controller中需要检测的页面的头部,即可:

   1:  [ValidateInput(false)]
   2:  [FilterChars]
   3:  public ActionResult Index(TestModel t)
   4:  {
   5:       ViewData["ConvertedModel"] = t;
   6:       return View();
   7:  }

这样,我们就完成了对输入数据的过滤操作,下面看看结果吧:

QQ截图20140422211039

 

 

 

 

 

 

 

 

 

我们可以清楚的看到,输入结果,输出后,一对尖角号被转义了。

posted on 2014-04-22 21:12  程序诗人  阅读(4950)  评论(1编辑  收藏  举报