Dzwebs.Net

撰写电脑技术杂文十余年

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

Admin | 2009-2-27 17:29:54 | 被阅次数 | 8241

温馨提示!

如果未能解决您的问题,请点击搜索;登陆可复制文章,点击登陆

  在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;
    }


该杂文来自: 网站开发杂文

上一篇:IIS服务器不支持Ajax无刷新的解决办法

下一篇:如何让别人无法查看上传到虚拟空间的网站文件代码

网站备案号:

网站备案号:滇ICP备11001339号-7

版权属性:

Copyright 2007-2021-forever Inc. all Rights Reserved.

联系方式:

Email:dzwebs@126.com QQ:83539231 访问统计