1. 程式人生 > >ASP.net防SQL注入(簡單)

ASP.net防SQL注入(簡單)

一,驗證方法

 /// <summary>
  ///SQL注入過濾
  /// </summary>
  /// <param name="InText">要過濾的字串</param>
  /// <returns>如果引數存在不安全字元,則返回true</returns>
  public static bool SqlFilter2(string InText)
  {
   string word="and|exec|insert|select|delete|update|chr|mid|master|or|truncate|char|declare|join";
   if(InText==null)
    return false;
   foreach(string i in word.Split('|'))
   {
    if((InText.ToLower().IndexOf(i+" ")>-1)||(InText.ToLower().IndexOf(" "+i)>-1))
    {
     return true;
    }
   }
   return false;
  }

二,Global.asax 事件

  /// <summary>
  /// 當有資料時交時,觸發事件
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  protected void Application_BeginRequest(Object sender, EventArgs e)
  {
   //遍歷Post引數,隱藏域除外
   foreach(string i in this.Request.Form)
   {
    if(i=="__VIEWSTATE")continue;
    this.goErr(this.Request.Form[i].ToString());    
   }
   //遍歷Get引數。
   foreach(string i in this.Request.QueryString)
   {
    this.goErr(this.Request.QueryString[i].ToString());    
   }
  }

三,Global中的一個方法

  /// <summary>
  /// 校驗引數是否存在SQL字元
  /// </summary>
  /// <param name="tm"></param>
  private void goErr(string tm)
  {
   if(WLCW.Extend.CValidity.SqlFilter2(tm))
    this.Response.Redirect("/error.html");
  }