且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

登录密码验证

更新时间:2023-12-03 14:42:16

我们是对的!如果密码与会话匹配,则设置该会话,因为那是"if(passord == ....)"之后的第一行代码,但是每次都会命中ResponseRedirect.


尝试

Wes is right! if the passwords match the session is set because that is the first line of code after the "if(passord==....)" But the ResponseRedirect is hit every time.


try to

if (password == TextBox2.Text)
{ 
  Session["name"] = TextBox1.Text;
  Response.Redirect("AfterLogin.aspx?Name="+TextBox1.Text);
}



如果您已连接调试器,您将看到此行为.如果您的代码也更简洁一点,您可能会看到它.按CTRL + K D在VS中格式化代码.

代码的另一件事是您正在执行2 ExecuteScalar().您只需要一个.我用一种更简洁的方式重写了您的代码:



If you had attached the debugger you would have seen this behavior. You would probably seen it if your code was a little cleaner also. Hit CTRL+K D to format your code in VS.

Another thing with your code is that you are doing 2 ExecuteScalar(). You only need one. I have rewritten your code in a slightly cleaner way:

protected void Button1_Click(object sender, EventArgs e)
{
    // I always user variables. Then I don't have refer to textboxes each time.
    string username = Textbox1.Text;
    string password = TextBox2.Text;

    SqlConnection conn = new SqlConnection("ConnectionString");
            
    string sql = "select password from Reg where UserName=@Username";
    SqlCommand cmd = new SqlCommand(sql, conn);

    // use sql parameter to avoid sql injection!
    cmd.Parameters.AddWithValue("@Username", username);
            
    //Open the connection as close to any other db-stuff.
    // don't keep it open unless you have to use it
    conn.Open();

    // ExecuteScalar() (which is an object) can be null!
    // using Convert.ToString() prevents any Null Reference Exception.
    // Convert.ToString(null) returns string.Empty
    string pwdFromDb = Convert.ToString(cmd.ExecuteScalar());

    // All database stuff is ok. 
    cmd.Dispose();
    conn.Close(); // Always close DB connection when done!


    // Now we can do the redirect logic
    if(pwdFromDb == password) // this will make your pwd case sensitive
    {
        // user is found and passwords are equal
        // Set session and redirect user
        Session["name"] = username;
        Response.Redirect("AfterLogin.aspx?Name=" + username);
    }
    else 
    {
        // userFoundAndPwdIsOk is false..
        Label2.Visible = true;
        Label2.Text = "invalid username or password";
    }
}



给您的一些提示:
1)在您的sql中发送变量时,请始终使用命令参数! 2)在if(){...}
周围使用方括号 3)切勿将密码存储为明文.对其进行哈希处理并使用密码盐.



A few tips for you:
1) Always use command parameters when sending variables in your sql!
2) Use brackets around your if''s if(){...}
3) Never store passwords as clear text. Hash it and use a password salt.

for (int i = 4; i < 1000; i++)
{
    Console.WriteLine(i + ") ALWAYS use command parameters!");
}