The following is a. net program to prevent SQL injection. The method is as follows: add the following code to the Global. asax file:
/// <Summary> /// prevent SQL Injection /// </summary> /// <param> </param> 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 = "error. aspx "; // 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 {// handle user submitted information! }}/// <Summary> /// analyze whether the user request is normal /// </summary> /// <param> input the user to submit data </param> /// <returns> whether the returned result contains the SQL injection attack code </returns> private bool ProcessSqlStr (string Str) {bool ReturnValue = true; try {if (Str. trim ()! = "") {String SqlStr = "and. exec. insert. select. delete. update. count. *. chr. mid. master. truncate. char. declare "; string [] anySqlStr = SqlStr. split ('. '); foreach (string ss in anySqlStr) {if (Str. toLower (). indexOf (ss) >=0) {ReturnValue = false; break ;}}} catch {ReturnValue = false;} return ReturnValue ;}# endregion method 2 is as follows: add a class SqlZr in the App_Code folder. cs has the following content: public class SqlZr {public SqlZr () {// TODO: add the constructor logic here //} public static string DelSQLStr (string str) {if (str = null | str = "") return ""; str = str. replace (";", ""); str = str. replace ("'", ""); str = str. replace ("&", ""); str = str. replace ("% 20", ""); str = str. replace ("--", ""); str = str. replace ("=", ""); str = str. replace ("<", ""); str = str. replace (">", ""); str = str. replace ("%", ""); str = str. replace ("+", ""); str = str. replace ("-", ""); str = str. replace ("=", ""); str = str. replace (",", ""); return str ;}}
Then
Request. QueryString ["id"]Changed:
SqlZr
. DelSQLStr (Request. QueryString ["id"])You can.