le mie informazioni di contatto
Posta[email protected]
2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Per verificare se i dati immessi dall'utente contengono istruzioni di attacco SQL injection in C# WinForms, è possibile utilizzare diversi metodi per rilevare e prevenire SQL injection. Ecco alcuni metodi comuni:
Le query con parametri rappresentano la procedura migliore per impedire l'iniezione SQL passando l'input dell'utente come parametri alla query SQL, anziché incorporarlo direttamente nella stringa SQL. Ciò garantisce che l'input dell'utente non venga interpretato come codice SQL.
- using System.Data.SqlClient;
-
- public void ExecuteQuery(string userInput)
- {
- string connectionString = "数据库连接字符串";
- string query = "SELECT * FROM Users WHERE Username = @Username";
-
- using (SqlConnection connection = new SqlConnection(connectionString))
- using (SqlCommand command = new SqlCommand(query, connection))
- {
- command.Parameters.AddWithValue("@Username", userInput);
-
- connection.Open();
- SqlDataReader reader = command.ExecuteReader();
- while (reader.Read())
- {
- // Process the data
- }
- }
- }
Caratteri e parole chiave SQL injection comuni come virgolette singole ('
),Virgolette ("
), punto e virgola (;
), simbolo di commento (--
), nonché parole chiave SQL comuni come SELECT
、INSERT
、DELETE
、UPDATE
、DROP
eccetera).
- public bool IsSqlInjection(string input)
- {
- string[] sqlCheckList = { "SELECT", "INSERT", "UPDATE", "DELETE", "DROP", "--", ";", "'" };
- foreach (string item in sqlCheckList)
- {
- if (input.IndexOf(item, StringComparison.OrdinalIgnoreCase) >= 0)
- {
- return true;
- }
- }
- return false;
- }
-
-
- string userInput = txtUserInput.Text;
- if (IsSqlInjection(userInput))
- {
- MessageBox.Show("输入包含不安全的字符,请重新输入。");
- }
- else
- {
- // 继续处理用户输入
- ExecuteQuery(userInput);
- }
L'utilizzo di un framework ORM (Object Relational Mapping) come Entity Framework può ridurre notevolmente il rischio di SQL injection poiché il framework ORM gestisce automaticamente le query con parametri.
- using (var context = new YourDbContext())
- {
- var user = context.Users.SingleOrDefault(u => u.Username == userInput);
- if (user != null)
- {
- // Process the user data
- }
- }