Does asp.net protect against sql injection attacks Does asp.net protect against sql injection attacks asp.net asp.net

Does asp.net protect against sql injection attacks


No. As long as you're supplying the SQL, it's up to you to be smart in how you use the controls.

That usually means sanitizing input and using Parameterized Queries or Stored Procedures over dynamic SQL strings.

If the control is generating the queries for you (like the Membership Controls, etc.) then you're well protected.


Yes and no.

ADO.NET has very good support for parameterization, and when you use it properly, the parameter values will be automatically sanitized to prevent SQL injection. So you can add parameters to a SqlCommand (or a SqlDataSource control) without worrying too much about what's in them.

The good news is that parameterizing your stuff is really easy. I'll show you a C# example for doing it programmatically, but you can do it declaratively with server controls if you prefer.

The bad news is that just like anything else, you still need to think about what you're doing. Any string from an unsafe source must be parameterized if you want to have any security. If you paste it verbatim into the query, you'll have bypassed ADO.NET's security features.

Secure:

string name = txtName.Text;sqlCommand.CommandText = "select * from product where name = @name";sqlCommand.Parameters.AddWithValue("name", name);

Not secure:

string name = txtName.Text;sqlCommand.CommandText = "select * from product where name = " + name;

If anything in your SQL query comes straight from the user, you need to put it in a parameter or all bets are off. And just like almost anything else, it's possible to shoot yourself in the foot if you really want to. For example, you could take SQL code, put it in a parameter, and pass it to a SQL EXEC statement. But you wouldn't do that, would you, because it is a Very Bad Idea.

Still not secure (yes, I saw this in production code)!

string sql = "select * from product where name = " + txtName.Text;sqlCommand.CommandText = "exec(@sql)";sqlCommand.Parameters.AddWithValue("sql", sql);

TL;DR: ADO.NET has great features to stop SQL injection, but only if you to use them correctly.


Most ASP.Net controls (except for DataGrid) do not use SQL at all.

If you have your own SQL in your code (using SqlCommands), you don't get any free protection; you need to use parameters.

The few controls that do use SQL (SqlDataSource and the membership framework) do use parameters and are safe against injection.