欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

防止SQL注入的ASP.NET方法实例解析

程序员文章站 2022-05-27 09:32:57
...
最近接手别人一个项目,发现存在SQL注入漏洞,因为不想改太多代码,所以那种参数法防注入呢我就用不着了。只能用传统的笨一点的办法了。

1、新建Global.asax文件。

2、加入如下代码:

void Application_BeginRequest(object sender, EventArgs e)
{
    bool result = false;
    if (Request.RequestType.ToUpper() == "POST")
    {
       //post方式的我就不写了。
    }
    else
    {
      result = ValidUrlGetData();
    }
    if (result)
    {
      Response.Write("您提交的数据有恶意字符!");
      Response.End();
    }
}
/// <summary>
/// 获取QueryString中的数据
/// </summary>
public static bool ValidUrlGetData()
{
    bool result = false;
    for (int i = 0; i < HttpContext.Current.Request.QueryString.Count; i++)
    {
      result = Validate(HttpContext.Current.Request.QueryString[i].ToString());
      if (result)
      {
        break;
      }//如果检测存在漏洞
    }
    return result;
}
public static string []strs = new string[] {"select","drop","exists","exec","insert","delete","update","and","or","user" };//此处我随便加了几个,大家可以多加点哈。
public static bool Validate(string str)
{
    for (int i = 0; i < strs.Length; i++)
    {
      if (str.IndexOf(strs[i]) != -1)
      {
        return true;
        break;
      }
    }
    return false;
}

以上就是防止SQL注入的ASP.NET方法实例解析的详细内容,更多请关注其它相关文章!

相关标签: ASP.NET SQL注入