[英]How to deal with this SQL injection warning (CA2100)
以下是我從 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 是不可接受的,因為我希望它是一個參數。
我知道這個問題很老,但也許這會幫助有同樣問題的人。 我還使用了存儲過程,因此使用 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")]
嘗試將CommandText
更改為string
而不是String
。
我嘗試使用時遇到了同樣的問題
new SqlCommand($"Select {1}", sqlConnection) // CA2100 warning
但是當我將其更改為直接字符串時,它起作用了
new SqlCommand("Select 1", sqlConnection) // no warning
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.