The following provides a. net program to prevent SQL injection (filter sensitive statements for reference only): Add the following code under the Global. asax file:
Void Application_BeginRequest (Object sender, EventArgs e)
{
StartProcessRequest ();
}
# Region SQL injection attack code analysis
/// <Summary>
/// Process user-submitted requests
/// </Summary>
Private void StartProcessRequest ()
{
Try
{
String getkeys = "";
String sqlErrorPage = ".../default. aspx"; // error prompt page for redirection
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
{
// Error handling: process user submitted information!
}
}
/// <Summary>
/// Analyze whether the user request is normal
/// </Summary>
/// <Param name = "Str"> input user to submit data </param>
/// <Returns> whether SQL injection attack code is returned </returns>
Private bool ProcessSqlStr (string Str)
{
Bool ReturnValue = true;
Try
{
If (Str. Trim ()! = "")
{
String SqlStr = "and merge exec values insert into select values delete values update values count distinct * distinct chr values mid weight master values truncate character char values declare ";
String [] anySqlStr = SqlStr. Split ('hangzhou ');
Foreach (string ss in anySqlStr)
{
If (Str. ToLower (). IndexOf (ss)> = 0)
{
ReturnValue = false;
Break;
}
}
}
}
Catch
{
ReturnValue = false;
}
Return ReturnValue;
}
# Endregion