我继承了正在修复安全漏洞的代码。调用存储过程时处理 SQL 注入(inject)的最佳做法是什么?
代码是这样的:
StringBuilder sql = new StringBuilder("");
sql.Append(string.Format("Sp_MyStoredProc '{0}', {1}, {2}", sessionid, myVar, "0"));
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["Main"].ToString()))
{
cn.Open();
using (SqlCommand command = new SqlCommand(sql.ToString(), cn))
{
command.CommandType = CommandType.Text;
command.CommandTimeout = 10000;
returnCode = (string)command.ExecuteScalar();
}
}
我只是对常规 SQL 查询执行相同的操作,并使用 AddParameter
添加参数,正确吗?
最佳答案
问。处理 SQL 注入(inject)的最佳实践是什么?
一个。使用 parameterised queries
例子:
using (SqlConnection connection = new SqlConnection(connectionString)) { // Create the command and set its properties. SqlCommand command = new SqlCommand(); command.Connection = connection; command.CommandText = "SalesByCategory"; command.CommandType = CommandType.StoredProcedure; // Add the input parameter and set its properties. SqlParameter parameter = new SqlParameter(); parameter.ParameterName = "@CategoryName"; parameter.SqlDbType = SqlDbType.NVarChar; parameter.Direction = ParameterDirection.Input; parameter.Value = categoryName; // Add the parameter to the Parameters collection. command.Parameters.Add(parameter); // Open the connection and execute the reader. connection.Open(); SqlDataReader reader = command.ExecuteReader(); . . . }
关于c# - 调用存储过程时处理 SQL 注入(inject)的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14905917/