在最近的项目中自己写了一段处理过滤非法字符的函数
原理:
1:首先判断页面的提交方式只有在post的情况下才进行过滤非法字符
2:将所以form表单中的数据保存到一个allvalue中
3:判断缓存是否过期 过期时从数据库重新读取数据,并将其保存到缓存中 未过期则从缓存中读取数据
4:将allvalue中的值与缓存中的比较判断是否存在非法字段
 
 
     public void IfNoKeyWord()
        {
            if (HttpContext.Current.Request.HttpMethod == "POST")//form表单提交情况下
            {
                string allValue = string.Empty;
                for (int i = 0; i < HttpContext.Current.Request.Form.Count; i++)
                {
                    allValue += HttpContext.Current.Request.Form[i] + "|";//存储一个页面的所以form提交的内容
                }
                CSqlCommand cmd = new CSqlCommand();
               
        //在页面缓存过期的情况下,从数据库中读取数据;有缓存的情况下从缓存读取数据
                DataTable dt ;              
         if (Cache["LastCache"] == null)
                {   
          dt=cmd.getDataTable("select keywords from t_keywords");
                    Cache.Add("LastCache", dt, null, DateTime.Now.AddDays(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null);
                }
        else
                {
                 dt = (DataTable)Page.Cache["LastCache"];
                 }
 
        //对比查找
                  for (int j = 0; j < dt.Rows.Count; j++)
                {
                    if (allValue.IndexOf(dt.Rows[j][0].ToString()) > -1)
                    {
                        ZbUtils.alert("你的输入内容中包含非法字符:【" + dt.Rows[j][0].ToString() + "】!", " window.history.back(-1);", true);
                    }
                }
            }
        }
 
在页面basepage初始化的时候调用他
 protected override void OnInit(EventArgs e)
        {
            //可更改检测模式
            if (!CheckPower())
                return;
            CurrentUserId = Convert.ToInt32(Session["UserID"]);
            CurrentUserName = Session["UserName"].ToString();
            CurrentUserType = Convert.ToInt32(Session["UserType"]);
            IfNoKeyWord();////////
            base.OnInit(e);
        }