How can I avoid SQL injection attacks in my ASP.NET application? How can I avoid SQL injection attacks in my ASP.NET application? asp.net asp.net

How can I avoid SQL injection attacks in my ASP.NET application?


Even though your question is very generic, a few rules always apply:

  • Use parameterized queries (SqlCommand with SqlParameter) and put user input into parameters.
  • Don't build SQL strings out of unchecked user input.
  • Don't assume you can build a sanitizing routine that can check user input for every kind of malformedness. Edge cases are easily forgotten. Checking numeric input may be simple enough to get you on the safe side, but for string input just use parameters.
  • Check for second-level vulnerabilites - don't build SQL query strings out of SQL table values if these values consist of user input.
  • Use stored procedures to encapsulate database operations.


Use Prepared Statements (link to an ASP.NET tutorial that uses prepared statements in the 'To add nodes for products' section). that's all there is to it.

Well, that or use an ORM, like Linq to SQL or NHibernate, they internally use prepared statements.


Use parameters! It really is that simple :-)

Create your queries like this (for MS Sql server with C#):

SqlCommand getPersons = new SqlCommand("SELECT * FROM Table WHERE Name = @Name", conn); 

Here @Name is the parameter where you want to avoid sql injection and conn is an SqlConnection object.Then to add the parameter value you do the following:

getPersons.Parameters.AddWithValue("@Name", theName);

Here theName is a variable that contains the name you are searching for.

Now it should be impossible to do any sql injections on that query.

Since it is this simple there is no reason not to use parameters.