2

以下是我从 Microsoft 页面获得的代码:SqlCommand

public static Int32 ExecuteNonQuery(String connectionString, String commandText, CommandType commandType, params SqlParameter[] parameters)
{
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            using (SqlCommand cmd = new SqlCommand(commandText, conn))
            {
                // There're three command types: StoredProcedure, Text, TableDirect. The TableDirect 
                // type is only for OLE DB.  
                cmd.CommandType = commandType;
                cmd.Parameters.AddRange(parameters);

                conn.Open();
                return cmd.ExecuteNonQuery();
            }
        }
}

但是,VS 代码分析仍然抱怨“CA2100”:

警告 CA2100 在“FlexClaimFormRepository.ExecuteNonQuery(string, string, CommandType, params SqlParameter[])”中传递给“SqlCommand.SqlCommand(string, SqlConnection)”的查询字符串可能包含以下变量“commandText”。如果这些变量中的任何一个可能来自用户输入,请考虑使用存储过程或参数化 SQL 查询,而不是使用字符串连接构建查询。

我知道警告存在的确切原因,但是关于如何摆脱它的任何想法?鉴于在函数内设置 commandText 是不可接受的,因为我希望它是一个参数。

4

2 回答 2

1

我知道这个问题很老,但也许这会帮助有同样问题的人。我还使用了存储过程,因此使用 Microsoft 的这篇文章中的信息抑制了警告: https ://docs.microsoft.com/en-us/visualstudio/code-quality/in-source-suppression-overview?view =vs-2019

这是我添加到方法中的属性:

[System.Diagnostics.CodeAnalysis.SuppressMessage("Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "Method already uses a Stored Procedure")]
于 2019-11-27T16:44:36.120 回答
0

尝试更改CommandText为 astring而不是String.

我尝试使用时遇到了同样的问题

new SqlCommand($"Select {1}", sqlConnection) // CA2100 warning

但是当我将其更改为直接字符串时,它起作用了

new SqlCommand("Select 1", sqlConnection) // no warning

于 2020-07-31T09:48:34.323 回答