[推薦]ASP.Net程式防注入通用源碼

來源:互聯網
上載者:User

防止sql注入,通常一個一個檔案修改不僅麻煩而且還有漏掉的危險,下面我說一上如何從整個系統防止注入。

做到以下三步,相信的程式將會比較安全了,而且對整個網站的維護也將會變的簡單。

一、資料驗證類:
parameterCheck.cs

 

public class parameterCheck{
    public static bool isEmail(string emailString){
        return System.Text.RegularExpressions.Regex.IsMatch(emailString, "['\\w_-]+(\\.['\\w_-]+)*@['\\w_-]+(\\.['\\w_-]+)*\\.[a-zA-Z]{2,4}");
    }
    public static bool isInt(string intString){
        return System.Text.RegularExpressions.Regex.IsMatch(intString ,"^(\\d{5}-\\d{4})|(\\d{5})$");
    }
    public static bool isUSZip(string zipString){
        return System.Text.RegularExpressions.Regex.IsMatch(zipString ,"^-[0-9]+$|^[0-9]+$");
    }
}

二、Web.config

在你的Web.config檔案中,在<appSettings>下面增加一個標籤:如下

 <appSettings>
    <add key="safeParameters" value="OrderID-int32,CustomerEmail-email,ShippingZipcode-USzip" />
</appSettings>

其中key是<saveParameters>後面的值為"OrderId-int32"等,其中"-"前面表示參數的名稱比如:OrderId,後面的int32表示資料類型。

三、Global.asax

在Global.asax中增加下面一段:

 

protected void Application_BeginRequest(Object sender, EventArgs e){
    String[] safeParameters = System.Configuration.ConfigurationSettings.AppSettings["safeParameters"].ToString().Split(',');
    for(int i= 0 ;i < safeParameters.Length; i++){
        String parameterName = safeParameters.Split('-')[0];
        String parameterType = safeParameters.Split('-')[1];
        isValidParameter(parameterName, parameterType);
    }
}

public void isValidParameter(string parameterName, string parameterType){
    string parameterValue = Request.QueryString[parameterName];
    if(parameterValue == null) return;

    if(parameterType.Equals("int32")){
        if(!parameterCheck.isInt(parameterValue)) Response.Redirect("parameterError.aspx");
    }
    else if (parameterType.Equals("double")){
        if(!parameterCheck.isDouble(parameterValue)) Response.Redirect("parameterError.aspx");
    }
    else if (parameterType.Equals("USzip")){
        if(!parameterCheck.isUSZip(parameterValue)) Response.Redirect("parameterError.aspx");
    }
    else if (parameterType.Equals("email")){
        if(!parameterCheck.isEmail(parameterValue)) Response.Redirect("parameterError.aspx");
    }
}

以後需要修改的時候我們只需要修改以上三個檔案,對整個系統的維護將會大大提高效率,當然你可以根據自己的需要增加其它的變數參數和資料類型。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.