先看一下MSDN對Global.asax的解釋:
Global.asax 檔案(也稱為 ASP.NET 應用程式檔案)是一個可選的檔案,該檔案包含響應 ASP.NET 或 HTTP 模組所引發的應用程式層級和會話層級事件的代碼。Global.asax 檔案駐留在 ASP.NET 應用程式的根目錄中。運行時,分析 Global.asax 並將其編譯到一個動態產生的 .NET Framework 類,該類是從 HttpApplication 基類派生的。配置 ASP.NET,以便自動拒絕對 Global.asax 檔案的任何直接的 URL 請求;外部使用者不能下載或查看其中的代碼。
所以防範SQL注入我們可以通過Global.asax入手,因為所有請求都要先執行這個檔案的相關方法。
以下是通過Global.asax防範SQL注入的範例程式碼:
<%@ Application Language="C#" %>
<script runat="server">
void Application_BeginRequest(object source, EventArgs e)
{
StartProcessRequest();
}
#region SQL注入式攻擊代碼防範
///
/// 處理使用者提交的請求
///
private void StartProcessRequest()
{
try
{
string getkeys = "";
string sqlErrorPage = "http://www.cqun.com";
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].ToLower()))
{
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 (!ProcessSqlStr(System.Web.HttpContext.Current.Request.Form[getkeys].ToLower()))
{
System.Web.HttpContext.Current.Response.Redirect (sqlErrorPage);
System.Web.HttpContext.Current.Response.End();
}
}
}
}
catch
{
// 錯誤處理: 處理使用者提交資訊!
}
}
///
/// 分析使用者請求是否正常
///
/// 傳入使用者提交資料
/// 返回是否含有SQL注入式攻擊代碼
private bool ProcessSqlStr(string Str)
{
bool ReturnValue = true;
try
{
if (Str != "" && Str != null)
{
string SqlStr = "";
if (SqlStr == "" || SqlStr == null)
{
SqlStr = "'|exec|insert|delete|update|chr|mid|master|truncate|char|declare";
}
string[] anySqlStr = SqlStr.Split('|');
foreach (string ss in anySqlStr)
{
if (Str.IndexOf(ss) >= 0)
{
ReturnValue = false;
}
}
}
}
catch
{
ReturnValue = false;
}
return ReturnValue;
}
#endregion
</script>