When I'am debugging my console says that my reader has no rows. Below you can find the code.
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();
}
The program skips the while loop completely. I have been searching for a while but could not find the answer maybe you guys see what is wrong.
usernameandpassword? can you put a breakpoint and confirm that you have right values and your select does return data? also, shouldn't your query put username and password as quoted string?SELECT * FROM [User] WHERE Username = '@Username' and Password = '@Password';