我一直在使用ASP创建简单的网站,但是不确定如何添加参数化查询以避免任何SQL Injection攻击,有人可以帮助我做到这一点吗?我总是遇到错误,而且已经进行了一个多星期仍然我不知道。下面我附上我的简单代码。
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string sql = "Select * From Users Where UserID='" + txtUser.Text + "' And Password='" + txtPwd.Text + "'";
con.Open();//opens the connection
//create the command object
cmd = new SqlCommand(sql, con);
//assigns the result to the reader
dr = cmd.ExecuteReader();
dr.Read();//read the record's data
//if there's a matching record found
if (dr.HasRows)
{
if (dr["UserType"].Equals("admin"))
{
Response.Redirect("dhome.aspx");
}
else if (dr["UserType"].Equals("staff"))
{
Response.Redirect("shome.aspx");
}
else if (dr["UserType"].Equals("member"))
{
Response.Redirect("mhome.aspx");
}
}
else
{
lblAlert.Text = "Invalid username or password!";
}
dr.Close(); //close the data reader
con.Close();//close the connection //declaration of data access components
}
答案 0 :(得分:1)
您应使用SqlCommand.Parameters.Add()
添加它们:
using (SqlConnection con = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand("Select * From Users Where UserID=@username And Password=@password", con);
cmd.Parameters.Add("@username", SqlDbType.VarChar).Value = username;
cmd.Parameters.Add("@password", SqlDbType.VarChar).Value = password;
//rest of the code ...
}
答案 1 :(得分:0)
您需要使用SqlCommand.Parameters.Add
。您还应该实施dispose(通过使用块或调用Dispose
)以在使用后释放资源:
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string sql = "Select * From Users Where UserID=@user And Password=@pwd";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.Add("@user", SqlDbType.VarChar);
command.Parameters["@user"].Value = "value";
command.Parameters.Add("@pwd", SqlDbType.VarChar);
command.Parameters["@pwd"].Value = "value";
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
// read row
}
}
}