.net全站过滤url危险参数,防注

在global文件 void Application_BeginRequest(object sender, EventArgs e)中添加如下代码:

    void Application_BeginRequest(object sender, EventArgs e)

    {

        //遍历Post参数,隐藏域除外 

        if (Regex.IsMatch(Request.RawUrl.ToLower(), @"/manager/")==false)

            for (int i=0; i < Request.Form.Count;i++)

            {

                if (Request.Form[i].ToString() == "__VIEWSTATE") continue;

                if (IsDanger(Request.Form[i].ToString()))

                {

                    Response.Write("您提交的内容中含有非法字符,已经被拒绝.");

                    Response.End();

                }

            } 

        //过滤所有Url中的危险字符串

        if (Request.QueryString.Count > 0 && Regex.IsMatch(Request.RawUrl.ToLower(), @"\.aspx") == true && Regex.IsMatch(Request.RawUrl.ToLower(), @"fckeditor") == false)//如果防止截获fckeditor正常的Url,必须验证".aspx"

        {

            string Temp = "";

            //string Url = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.LastIndexOf("?"));

            string Url = Request.RawUrl.Substring(0, Request.RawUrl.LastIndexOf("?"));

            for (int i = 0; i < this.Request.QueryString.Count; i++)

            {

                try

                {

                    Temp = HandleRequestParam(this.Request.QueryString[i].ToString());

                    Url += i == 0 ? "?" : "&";

                    Url += Request.QueryString.Keys[i].ToString() + "=" + Temp;

                }

                catch { }

            }

            //if (Url.Length < Request.Url.AbsoluteUri.Length)

            //    Response.Redirect(Url);

            Context.RewritePath(Url);//可以用Response.Redirect和Context.RewritePath

        }

        //全站防止页面缓存

        Response.Buffer = true;

        Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);

        Response.Expires = 0;

        Response.CacheControl = "no-cache";

    }

    protected bool IsDanger(string InText)

    {

        string word = @"exec|insert|select|delete|update|master|truncate|char|declare|join|iframe|href|script|<|>|request";

        if (InText == null)

            return false;

        if (Regex.IsMatch(InText,word))

            return true;

        return false;

    }

posted on 2011-03-11 15:33  MyBeN  阅读(1388)  评论(0编辑  收藏  举报

导航