How to prevent SQL injection on asp.net

To enter email into the text box by the user, I perform a client-side check to see if the email is really or not.

 string emailexist = "SELECT COUNT(DISTINCT UserID) as count FROM tbl_user WHERE Email=@Email ";     


   <asp:RegularExpressionValidator ID="RegularExpressionValidator2" ValidationGroup="Login" ControlToValidate="txtUserName"
                            ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" CssClass="Error"
                             runat="server" />

is a regular expression sufficient to prevent the embedding of SQL code for email.

Other text:

   string groupExistQuery = "SELECT COUNT(DISTINCT GroupID) as count FROM tbl_group WHERE GroupName=@GroupName";   

I make a server-side query to check if the group name entered by the user in the database is available, there is a strong ability to perform sql injection. How can I prevent this.

+5
source share
5 answers

SQL- ( .. ); @Email ( , ), SQL-.

SQL- ; , .

, :

var sql = "SELECT ...snip... WHERE Email='" + email + "'"; // BAD!!!!!

, SQL-. , , .

+8

, , , .

+6

, Direct SQL / .

+4
+1

- Microsoft Pattern and Practices .

, : SQL, , .

SQL-. , SQL- - , .

Here is an example from the document I provide above:

  DataSet userDataset = new DataSet();
  SqlDataAdapter myCommand = new SqlDataAdapter( 
             "LoginStoredProcedure", connection);
  myCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
  myCommand.SelectCommand.Parameters.Add("@au_id", SqlDbType.VarChar, 11);
  myCommand.SelectCommand.Parameters["@au_id"].Value = SSN.Text;

  myCommand.Fill(userDataset);
0
source

All Articles