asp.net MVC利用ActionFilterAttribute过滤关键字的方法

本文实例讲述了asp.net MVC利用ActionFilterAttribute过滤关键字的方法。分享给大家供大家参考,具体如下:

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

下面请看步骤:

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

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

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

using System.Web.Mvc;
using TinyFrame.Plugin.StrongTyped.Models;

namespace TinyFrame.Plugin.StrongTyped
{
  public class FilterCharsAttribute : ActionFilterAttribute
  {
    protected string parameterName = "t";
    protected TestModel model;
    
 public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
      base.OnActionExecuting(filterContext);
      
   //No Parameters, will return directly.
      if(!filterContext.ActionParameters.ContainsKey(parameterName))
        return;
      
   var t = filterContext.ActionParameters[parameterName] as TestModel;
      
   //No Entity data, will return directly
      if (t == null)
        return;
      
   //Replace chars that should be filtered
      if (!string.IsNullOrEmpty(t.TName))
        t.TName = t.TName.Replace("<", "&lt").Replace(">", "&gt");
      if (!string.IsNullOrEmpty(t.TSite))
        t.TSite = t.TSite.Replace("<", "&lt").Replace(">", "&gt");
    }
  }
}

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

public ActionResult Index(TestModel t)
{
     ViewData["ConvertedModel"] = t;
     return View();
}

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

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

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

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

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

[ValidateInput(false)]
[FilterChars]
public ActionResult Index(TestModel t)
{
   ViewData["ConvertedModel"] = t;
   return View();
}

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

asp.net MVC利用ActionFilterAttribute过滤关键字的方法

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

希望本文所述对大家asp.net程序设计有所帮助。