asp.net MVC中怎么利用ActionFilterAttribute过滤关键字

2023-05-29,

本篇文章给大家分享的是有关asp.net MVC中怎么利用ActionFilterAttribute过滤关键字,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

首先,当用户输入自己的名称的时候,带有类似<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 MVC中怎么利用ActionFilterAttribute过滤关键字.doc》

下载本文的Word格式文档,以方便收藏与打印。