Despite being one of the oldest security exploits SQL injects attacks are still an persistent threat. To protect agianst SQL injection in ASP.NET there is one golden rules.
Always use either parameterized queries or storage procedures for creating SQL commands.
Inexperienced developers often concatenate strings to create sql commands and just place raw text taken from controls such as textboxes and place it within the string as below:
SQLCmdStr = "Select * from users where username =' " & usernameTxt.Text & "'
This can allow a user to enter full SQL commands which will then be executed against the database. This can be averted by using a stored procedure:
con = new SqlConnection("connectionString..."); cmd = new SqlCommand("getEmployee", con); cmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = dropdown1.SelectedItem.text; cmd.CommandType = CommandType.StoredProcedure;
Or alternatively, creating the command string in the code using parameterized queries.
SQLCmdStr = “Select * from Employees where Lastname =@LastName” SQLCmd.Parameters.Add(New SQLParameter(“@LastName”, dropdown1.SelectedItem.text))
Note that this also applies to taking text from QueryStrings which can be edited by the user.