当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net MVC利用ActionFilterAttribute过滤关键字的方法

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

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

妖界y游记,卓意设计,cz3920

本文实例讲述了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("<", "<").replace(">", ">");
      if (!string.isnullorempty(t.tsite))
        t.tsite = t.tsite.replace("<", "<").replace(">", ">");
    }
  }
}

第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程序设计有所帮助。

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

相关文章:

验证码:
移动技术网