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

balaweblog picture balaweblog · Nov 20, 2008 · Viewed 26.4k times · Source

I need to avoid being vulnerable to SQL injection in my ASP.NET application. How might I accomplish this?

Answer

Tomalak picture Tomalak · Nov 20, 2008

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.