以前防sql注入都是当个验证的,觉得太麻烦了,今天找个全局验证的,分享给大家,希望对大家有帮助
在Web应用程序加全局Global.asax文件,加入Application_BeginRequest禁止提交特殊字符。
protected void Application_BeginRequest(Object sender, EventArgs e)
{
//遍历Post参数,隐藏域除外
foreach (string i in this.Request.Form)
{
if (i == "__VIEWSTATE") continue;
this.goErr(this.Request.Form[i].ToString());
}
//遍历Get参数。
foreach (string i in this.Request.QueryString)
{
this.goErr(this.Request.QueryString[i].ToString());
}
}
/// <summary>
///SQL注入过滤
/// </summary>
/// <param name="InText">要过滤的字符串</param>
/// <returns>如果参数存在不安全字符,则返回true</returns>
public static bool SqlFilter2(string InText)
{
string word = ConfigurationManager.AppSettings["RequestForbidWord"].ToString();
if (InText == null)
return false;
foreach (string i in word.Split('|'))
{
if ((InText.ToLower().IndexOf(i + " ") > -1) || (InText.ToLower().IndexOf(" " + i) > -1))
{
return true;
}
}
return false;
}
//// <summary>
/// 校验参数是否存在SQL字符
/// </summary>
/// <param name="tm"></param>
private void goErr(string tm)
{
//string Errorpage = ConfigurationManager.AppSettings["SqlErrorpage"].ToString();
if (SqlFilter2(tm))
{
this.Response.Redirect("/ErrorForm.aspx");
}
}
WEB.CONFIG文件 :
<add key="RequestForbidWord" value="and|exec|insert|select|delete|update|chr|mid|master|or|truncate|char|declare|join|script>|drop|alter|create"/>