以下是一個.net程式防止sql注入的方法,方式一如下:將下面的代碼加入到Global.asax檔案中:
///<summary> ///防止SQL注入 ///</summary> ///<param ></param> ///<param ></param> void Application_BeginRequest(Object sender, EventArgs e) { StartProcessRequest(); }
#region SQL注入式攻擊程式碼分析
///<summary> ///處理使用者提交的請求 ///</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 { // 錯誤處理: 處理使用者提交資訊! } } ///<summary> ///分析使用者請求是否正常 ///</summary> ///<param >傳入使用者提交資料 </param> ///<returns>返回是否含有SQL注入式攻擊代碼 </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方法二如下:在App_Code檔案夾中加一個類SqlZr.cs 其內容如下 public class SqlZr{ public SqlZr() { // // TODO: 在此處添加建構函式邏輯 // } 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; } }
再將所有項目中的
Request.QueryString["id"]改為:
SqlZr
.DelSQLStr(Request.QueryString["id"])即可