大众计算机学习网欢迎诸位!收藏本站注 册登 陆
常用教程:基础知识网络知识操作系统WPS网页制作数据库算法网页成功之路网络安全最新技术古典mid流行midmid背景下载中心
您现在的位置:首页 > 教程 > 文章页

使用字符过滤的方法防止ASP.NET网站被注入的代码示例

Admin | 2009-2-27 17:29:54 | ReadNums | 5275 | 标签 asp.net | 打印本页
     

  在global里加如下函数代码:

void Application_BeginRequest(Object sender, EventArgs e)
    {
        StartProcessRequest(); 
    }
private void StartProcessRequest()
    {
        try
        {
            string getkeys = "";
            string sqlErrorPage = "index.aspx";
            if (System.Web.HttpContext.Current.Request.QueryString != null)
            {

                for (int i = 0; i < System.Web.HttpContext.Current.Request.QueryString.Count; i++)
                {
                    getkeys = System.Web.HttpContext.Current.Request.QueryString.Keys[i];
                    if (!ProcessSqlStr(System.Web.HttpContext.Current.Request.QueryString[getkeys]))
                    {
                        System.Web.HttpContext.Current.Response.Redirect(sqlErrorPage);
                        System.Web.HttpContext.Current.Response.End();
                    }
                }
            }
            if (System.Web.HttpContext.Current.Request.Form != null)
            {
                for (int i = 0; i < System.Web.HttpContext.Current.Request.Form.Count; i++)
                {
                    getkeys = System.Web.HttpContext.Current.Request.Form.Keys[i];
                    if (getkeys == "__VIEWSTATE") continue;
                    if (!ProcessSqlStr(System.Web.HttpContext.Current.Request.Form[getkeys]))
                    {
                        System.Web.HttpContext.Current.Response.Redirect(sqlErrorPage);
                        System.Web.HttpContext.Current.Response.End();
                    }
                }
            }
        }
        catch
        {
            // 错误处理: 处理用户提交信息! 
        }
    }
    private bool ProcessSqlStr(string Str)
    {
        bool ReturnValue = true;
        try
        {
            if (Str.Trim() != "")
            {
                string SqlStr = "exec|insert|select|delete|master|update|truncate|declare";
                string[] anySqlStr = SqlStr.Split('|');
                foreach (string ss in anySqlStr)
                {
                  if(!Str.ToLower().Contains("updatepanel"))
                  {
                    if (Str.ToLower().IndexOf(ss) >= 0)
                    {
                        ReturnValue = false;
                        break;
                    }
                  }
                }
            }
        }
        catch
        {
            ReturnValue = false;
        }
        return ReturnValue;
    }


问题未解决:在线咨询

网友评论

(访客)
内容实用原创,讲得很好。
20xx年x月x日
(站长)
有问题请在线咨询。
20xx年x月x日