4

セキュリティホールを修正しているコードを継承しました。ストアドプロシージャが呼び出されたときにSQLインジェクションを処理するためのベストプラクティスは何ですか?

コードは次のようなものです。

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正しいものを使用してパラメーターを追加しますか?

4

1 に答える 1

11

Q. SQLインジェクションを処理するためのベストプラクティスは何ですか?

A.パラメータ化されたクエリを使用する

例:

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();
    .
    .
    .
}
于 2013-02-16T01:22:18.213 に答える