Is this Sql-injection-proof Asp.net code?

2019-04-11 16:36发布

Problem: I have a form with text values, and a function that must return a string query based on the values of the text values too.

Solution: I created a SQLCommand query with parameters, then I put the SQLCommand.CommandText to a string and I returned it (to the business logic that is going to handle the query)

Main Question: Is it sql-injection proof?

Code Example:

sQuery = "select * from xy where x like '%@txtNameParameter%'";

SqlCommand cmd = new SqlCommand(sQuery);

cmd.Parameters.Add("@txtNameParameter", SqlDbType.VarChar);
cmd.Parameters["@txtNameParameter"].Value = txtName.Text;

string query = cmd.CommandText;
return query;

Sub question if main question is ok: Should I put into parameters also values of a radiobutton and dropdownmenu or are they injection-proof?

1条回答
对你真心纯属浪费
2楼-- · 2019-04-11 17:01

What you are doing here is injection proof because you are not injecting anything. In fact, your parameter isn't even used (because the only reference to it is inside a string literal so the SQL Parser won't even see where you are attempting to use the parameter because it will treat it as a string literal.)

You may want to change that line of code to:

sQuery = "select * from xy where x like '%'+@txtNameParameter+'%'";

Which would make the SQL look like this:

select * from xy where x like '%'+@txtNameParameter+'%'

Which is just string concatenation in a place where a string is expected in the SQL command anyway.

However, your description of what you are doing with this afterwards possibly blows all that out of the water. I cannot understand why you would want to send just the where clause of the query to the business layer.

Also, the substringed WHERE clause will not contain the data you are putting in the parameter. So you are getting no more benefit that just returning

return "where x like '%@txtNameParameter%'";

The parameter value is lost.

查看更多
登录 后发表回答