c# - 调用存储过程时处理 SQL 注入(inject)的最佳实践

标签 c# .net sql-server stored-procedures sql-injection

我继承了正在修复安全漏洞的代码。调用存储过程时处理 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/

相关文章:

c# - WPF 包装面板中的 float 行为

.net - 替换 WPF 入口点

sql - 查找 SQL 中非空行的百分比

c# - 这个正则表达式的名称是什么?

c# - Active Directory 用户密码到期日期 .NET/OU 组策略

c# - 尝试连接到sql数据库时出现权限错误

c# - 如何让 BindingSource 知道其 DataSource 的变化?

c# - Facebook 使用 C# 使用 Graph API 检索数据

c# - 哪个性能更好,C# for 循环或 sql 中的游标(或 while 循环)?

sql-server - Linq 性能 : Two queries, 第一个立即响应,第二个非常慢