1 编写防止sql注入攻击的类
View Code
/// <summary>
/// 验证请求
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public static Boolean ValidUrlData(string request)
{
Boolean result = false;
if (request == "POST")
{
for (int i = 0; i < HttpContext.Current.Request.Form.Count; i++)
{
result = ValidData(HttpContext.Current.Request.Form[i].ToString());
if (result)
{
break;
}
}
}
else
{
for (int i = 0; i < HttpContext.Current.Request.QueryString.Count; i++)
{
result = ValidData(HttpContext.Current.Request.QueryString[i].ToString());
if (result)
{
break;
}
}
}
return result;
}
private static Boolean ValidData(string inputData)
{
if (Regex.IsMatch(inputData,GetRegesString()))
{
return true;
}
else
{
return false;
}
}
private static string GetRegesString()
{
string[] strBadChar = { "and", "exec", "insert", "delete", "update", "select", "count", "from" ,
"asc","char","or","%",":",";","\'\"","-","mid","master","truncate",
"declare","site name","net user","xp_cmdshell","/add","exec master dbo.xp_cmdshell",
"net localgroup administrators"};
string str_Regex=".*(";
for (int i = 0; i < strBadChar.Length - 1;i++ )
{
str_Regex += strBadChar[i] + "|";
}
str_Regex += strBadChar[strBadChar.Length - 1] + ").*";
return str_Regex;
}
2 在Global.asax 添加检查
View Code
protected void Application_BeginRequest(object sender, EventArgs e)
{
Boolean result = false;
result = RreventSqlHelper.ValidUrlData(Request .RequestType.ToUpper());
if (result)
{
Response.Write("您请求有恶意字符");
Response.End();
}
}
3 应用
View Code
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</div>
<div>
<asp:Button ID="btn1" Text="获取POST数据" runat =server onclick="btn1_Click" />
<asp:Button ID="btn2" Text="获取GET数据" runat =server onclick="btn2_Click" />
</div>
</form>
View Code
//Get发送
protected void btn2_Click(object sender, EventArgs e)
{
Response.Redirect("WebForm_RreventSql.aspx?a=1&b=2");
}
以上摘自:《Asp.net 4.0 权威指南》