这是一个防Sql注入的Asp.net代码吗?

Att*_*ila 3 asp.net parameters sql-injection sqlcommand sqlconnection

问题:我有一个带有文本值的表单,以及一个必须根据文本值的值返回字符串查询的函数.

解决方案:我使用参数创建了一个SQLCommand查询,然后我将SQLCommand.CommandText放到一个字符串中,然后将其返回(将要处理查询的业务逻辑)

主要问题:它是sql注入证明吗?

代码示例:

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;
Run Code Online (Sandbox Code Playgroud)

如果主要问题是好的子问题:我是否应该将参数放入radiobutton和dropdownmenu的值或者它们是否注入防护?

Col*_*kay 5

你在这里做的是注射证明,因为你没有注射任何东西.实际上,您的参数甚至没有被使用(因为它的唯一引用是在字符串文字内,因此SQL Parser甚至不会看到您尝试使用该参数的位置,因为它会将其视为字符串文字.)

您可能希望将该行代码更改为:

sQuery = "select * from xy where x like '%'+@txtNameParameter+'%'";
Run Code Online (Sandbox Code Playgroud)

哪个会使SQL看起来像这样:

select * from xy where x like '%'+@txtNameParameter+'%'
Run Code Online (Sandbox Code Playgroud)

这只是在SQL命令中预期字符串的地方的字符串连接.

但是,你对此后所做的描述可能会将所有这些都从水中吹走.我无法理解为什么你只想将查询的where子句发送到业务层.

此外,子字符WHERE子句将不包含您在参数中放入的数据.因此,您将无法获得更多的回报

return "where x like '%@txtNameParameter%'";
Run Code Online (Sandbox Code Playgroud)

参数值丢失.