我最近开始研究SQL注入,所以如果我犯了一个明显的错误,请原谅。我有一个查询返回数据库中的某些字段。我正在尝试参数化它,所以我可以避免SQL注入。我的代码在
之下protected string UserInfo()
{
string UsrName = User.Identity.Name;
using (SqlConnection connection = new SqlConnection(Common.ConnectionString))
{
UserDetail det = new UserDetail();
using (SqlCommand cmd = new SqlCommand("select FirstName=@fn,LastName=@ln,MobileNumber=@mn,EmailAddress=@ea from Users,OtherInfo where OTID = USERID AND UserName=@UserName"))
{
cmd.Parameters.AddWithValue("UserName", UsrName); // Works correctly for this
cmd.Parameters.AddWithValue("@fn" det.FirstName);
cmd.Parameters.AddWithValue("@ln" det.FirstName);
cmd.Parameters.AddWithValue("@mn" det.FirstName);
cmd.Parameters.AddWithValue("@ea" det.FirstName);
cmd.Connection = connection;
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
reader.Read();
info.FirstName = reader["FirstName"].ToString();
info.LastName = reader["LastName"].ToString();
info.TelNum = reader["MobileNumber"].ToString();
info.Email = reader["EmailAddress"].ToString();
}
}
}
}
我的UserDetail
具有以下属性:
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string TelNum { get; set; }
但它似乎只返回null
值?有谁知道我在哪里出错?
答案 0 :(得分:2)
我认为你并不想从你的UserDetail
对象中传入空值。您实际上是从null
传递UserDetail
值作为查询输出列的值。
尝试删除select
部分中的参数,将其从命令中删除,然后重试:
using (SqlCommand cmd = new SqlCommand("select FirstName,LastName,MobileNumber,EmailAddress from Users,OtherInfo where OTID = USERID AND UserName=@UserName"))
{
cmd.Parameters.AddWithValue("UserName", UsrName); // Works correctly for this
cmd.Connection = connection;
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
info.FirstName = reader["FirstName"].ToString();
info.LastName = reader["LastName"].ToString();
info.TelNum = reader["MobileNumber"].ToString();
info.Email = reader["EmailAddress"].ToString();
}
}
}