【发布时间】:2018-04-18 19:03:58
【问题描述】:
当我在调试时,我的控制台说我的阅读器没有行。 您可以在下面找到代码。
public ActionResult Login(LoginViewModel loginViewModel)
{
bool isSucces = false;
if (ModelState.IsValid)
{
SqlConnection conn = new SqlConnection(@"Data Source=DESKTOP-9DG53HK\TOMSQL;Initial Catalog=Webshop;Integrated Security=True");
conn.Open();
string username = loginViewModel._username;
string password = HashPassword(loginViewModel._username, loginViewModel._password);
SqlCommand cmd = new SqlCommand("SELECT * FROM [User] WHERE Username = @Username and Password = @Password;", conn);
cmd.Parameters.AddWithValue("@Username", username);
cmd.Parameters.AddWithValue("@Password", password);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
int Role = Convert.ToInt32(reader["Role"]);
}
}
else
{
Console.WriteLine("No rows found.");
}
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
bool loginSuccessful = ((ds.Tables.Count > 0) && (ds.Tables[0].Rows.Count > 0));
if (loginSuccessful)
{
//return View(new LoginViewModel(isSucces, Role));
}
else
{
Console.WriteLine("Invalid username or password");
}
}
return View();
}
程序完全跳过 while 循环。我已经搜索了一段时间,但找不到答案,也许你们看到了什么问题。
【问题讨论】:
-
您确定为
username和password发送正确的参数?你能放一个断点并确认你有正确的值并且你的选择确实返回数据吗?另外,您的查询不应该将用户名和密码作为引号字符串吗?SELECT * FROM [User] WHERE Username = '@Username' and Password = '@Password'; -
你是说查询返回的是数据库中的实际结果吗?
-
@Veljko89 用户名和密码的值正确。
-
@Veljko89 我也尝试了引用的字符串。没用。。
-
@Veljko89 引用参数将它们转换为 text。参数确保您永远不需要引用。如果你需要使用引号,说明你使用的是字符串连接,容易受到 SQL 注入的影响
标签: c# sqldatareader sqlclient