最好的办法就是不写拼接SQL,改用参数化SQL,推荐新项目使用。这里不做介绍,感兴趣的朋友可以自行搜索一下,本文介绍的方法适合老项目,就是没有使用参数化SQL开发的程序。
public class SqlFilter
{
public static void Filter()
{
string fileter_sql = "execute,exec,select,insert,update,delete,create,drop,alter,exists,table,sysobjects,truncate,union,and,order,xor,or,mid,cast,where,asc,desc,xp_cmdshell,join,declare,nvarchar,varchar,char,sp_oacreate,wscript.shell,xp_regwrite,',%,;,--";
try
{
// -----------------------防 Post 注入-----------------------
if (HttpContext.Current.Request.Form != null)
{
PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
//把 Form 属性改为可读写
isreadonly.SetValue(HttpContext.Current.Request.Form, false, null);
for (int k = 0; k System.Web.HttpContext.Current.Request.Form.Count; k++)
{
string getsqlkey = HttpContext.Current.Request.Form.Keys[k];
string sqlstr = HttpContext.Current.Request.Form[getsqlkey];
string[] replace_sqls = fileter_sql.Split(',');
foreach (string replace_sql in replace_sqls)
{
sqlstr = Regex.Replace(sqlstr, replace_sql, "", RegexOptions.IgnoreCase);
}
HttpContext.Current.Request.Form[getsqlkey] = sqlstr;
}
}
// -----------------------防 GET 注入-----------------------
if (HttpContext.Current.Request.QueryString != null)
{
PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
//把 QueryString 属性改为可读写
isreadonly.SetValue(HttpContext.Current.Request.QueryString, false, null);
for (int k = 0; k System.Web.HttpContext.Current.Request.QueryString.Count; k++)
{
string getsqlkey = HttpContext.Current.Request.QueryString.Keys[k];
string sqlstr = HttpContext.Current.Request.QueryString[getsqlkey];
string[] replace_sqls = fileter_sql.Split(',');
foreach (string replace_sql in replace_sqls)
{
sqlstr = Regex.Replace(sqlstr, replace_sql, "", RegexOptions.IgnoreCase);
}
HttpContext.Current.Request.QueryString[getsqlkey] = sqlstr;
}
}
// -----------------------防 Cookies 注入-----------------------
if (HttpContext.Current.Request.Cookies != null)
{
PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
//把 Cookies 属性改为可读写
isreadonly.SetValue(HttpContext.Current.Request.Cookies, false, null);
for (int k = 0; k System.Web.HttpContext.Current.Request.Cookies.Count; k++)
{
string getsqlkey = HttpContext.Current.Request.Cookies.Keys[k];
string sqlstr = HttpContext.Current.Request.Cookies[getsqlkey].Value;
string[] replace_sqls = fileter_sql.Split(',');
foreach (string replace_sql in replace_sqls)
{
sqlstr = Regex.Replace(sqlstr, replace_sql, "", RegexOptions.IgnoreCase);
}
HttpContext.Current.Request.Cookies[getsqlkey].Value = sqlstr;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}