Da black ninja Da black ninja - 3 months ago 9
ASP.NET (C#) Question

Redirect page after SQL query

Assuming that I'm on http://localhost:7924/default , and I type the login info , here is what happens in each scenario :



  1. If password is wrong (or correct) + login_name doesn't exist => refresh page

  2. If password is wrong + login_name exist (correct) => going to
    error_page

  3. If both are correct => redirected to CP.aspx




string text = username_login.Text;
string str2 = password_login.Text;
SqlConnection sqlcon = new SqlConnection(Functions.Auth());
SqlCommand sqlcmd = new SqlCommand();
sqlcmd.CommandText = "SELECT TOP 1 password FROM dbo.Accounts WHERE login_name = @login_name";
sqlcmd.Parameters.Add("@login_name", System.Data.SqlDbType.NVarChar).Value = text;
sqlcmd.CommandType = System.Data.CommandType.Text;
sqlcmd.Connection = sqlcon;
sqlcon.Open();
SqlDataReader sqlreader = sqlcmd.ExecuteReader();
string returnString = String.Empty;
while (sqlreader.Read())
{


if (sqlreader["password"].ToString() == Functions.CreateMD5Hash("5487" + str2.ToString()))
{
this.Session["logged_in"] = "true";
this.Session["username"] = text;
base.Response.Redirect("/CP.aspx");

}
else

{
base.Response.Redirect("/error_page?err=login-fail");
}

}


Both 2. & 3. are working as should be, however, the first one is not. I don't understand why It only refreshes the page instead of going to the error page since the details are wrong. (since It cannot make the comparison)

EDIT : I also checked if password is NULL => redirect to error_page but that refreshes the page as well.

Answer

You just need to check if it has any value.

if(sqlreader.HasRows)
{
    While...
}
else
{
   //refresh page code here
}

Also you might want to think about a better architect n-tie, Presentation Layer, Business Layer, Data Access Layer.

Comments