C#,Asp.net 防止Sql 注入代码

来源:互联网 发布:matlab禁忌搜索算法 编辑:程序博客网 时间:2024/05/10 18:20

下面说下网站防注入的几点要素。
一:丢弃SQL语句直接拼接,虽然这个写起来很快很方便。
二:如果用SQL语句,那就使用参数化,添加Param
三:尽可能的使用存储过程,安全性能高而且处理速度也快
四:屏蔽SQL,javascript等注入(很是主要的),对于每个文件写是不太可能的。所以要找到对所有文件起作用的办法。

 

方法一:使用参数化

 

 

 

 

SqlParameter

 

[] param = {

 

 

               new SqlParameter("@request_id",SqlDbType.Int,32),

 

 

                new SqlParameter("@request_name",SqlDbType.VarChar,50)

              };

param[0]=value1;

param[1]=value2;

 

 

SqlCommand cmd = new SqlCommand();

cmd.CommandText =

"select * from table1 where request_id=@request and request_name=@request_name";

 

 

方法二:使用字符串过滤类:

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;    }

    }

方法三:全局防止

step 1:在Web.config文件中, <appSettings>下面增加一个标签:如下
<appSettings>
<add key="safeParameters" value="OrderID-int32,CustomerEmail-email,ShippingZipcode-USzip" />
</appSettings>
其中key是 <saveParameters>后面的值为"OrderId-int32"等,其中"-"前面表示参数的名称比如:OrderId,后面的int32表示数据类型。

step 2:在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[i].Split('-')[0];
String parameterType = safeParameters[i].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("USzip")){
if(!parameterCheck.isUSZip(parameterValue)) Response.Redirect("parameterError.aspx");
}
else if (parameterType.Equals("email")){
if(!parameterCheck.isEmail(parameterValue)) Response.Redirect("parameterError.aspx");
}
}

 

欢迎大家附载别的好方法!!!

原创粉丝点击