我正在用 C# 验证表单,但我不知道我做错了什么。请帮我解决这个问题



我正在为来自数据库的表单数据创建一个验证,然后将其与文本框中输入的数据进行比较。无论我在文本框中输入正确或不正确的数据,它总是执行其他部分,请帮助。

c.Uname = Text1.Value.ToString();
c.Cnic  = Text2.Value.ToString();
c.pass = Text3.Value.ToString();
SqlConnection sqlConn = new SqlConnection(@"Data Source=DESKTOP-Q4AAHCG;Initial Catalog=practise;User ID=;Password=;Trusted_Connection=True");
SqlCommand sqlComm = new SqlCommand("select Uname , Cnic, password from carregister", sqlConn);
sqlConn.Open();
SqlDataReader dr = sqlComm.ExecuteReader();
while (dr.Read())
{
name = dr["Uname"].ToString();
cnic = dr["Cnic"].ToString();
passs = dr["password"].ToString();
if (name.Equals(c.Uname) && cnic.Equals(c.Cnic) && passs.Equals(c.pass))
{
Session["Uname"] = Text1.Value.ToString();
Session["cnic"] = Text2.Value.ToString();
Response.Redirect("Carloby.aspx");
}
else 
{
Response.Redirect("wrongidpass.aspx");
}
}

您正在读取用户表的所有行,并开始与收到的第一行进行比较。如果不匹配,则说明您已在重定向。。。

您可以只计算数据库中匹配的行,如果返回的不是1,则说明用户名或密码(或数据库(有错误。

c.Uname = Text1.Value.ToString();
c.Cnic  = Text2.Value.ToString();
//you don't store plaintext passwords in your db, do you?
c.pass = hash_the_password(Text3.Value.ToString());  
SqlConnection sqlConn = new SqlConnection(@"Data Source=DESKTOP-Q4AAHCG;Initial Catalog=practise;User ID=;Password=;Trusted_Connection=True");
SqlCommand sqlComm = new SqlCommand("SELECT COUNT(*) FROM carregister WHERE uname = @uname and cnic = @cnic and password = @hashedpassword", sqlConn);
sqlComm.Parameters.Add("@uname", SqlDbType.NVarchar).Value = c.Uname;
sqlComm.Parameters.Add("@cnic", SqlDbType.NVarchar).Value = c.Cnic;
sqlComm.Parameters.Add("@hashedpassword", SqlDbType.NVarchar).Value = c.pass;
sqlConn.Open();
if (Convert.ToInt32(sqlComm.ExecuteScalar()) == 1) {
//you have exactly one row where uname, cnic and password match the entered values
Session["Uname"] = Text1.Value.ToString();
Session["cnic"] = Text2.Value.ToString();
Response.Redirect("Carloby.aspx");
}
else 
{
//no row matched 
//(or more than one which is an error in the database, because uname should probably be unique)
Response.Redirect("wrongidpass.aspx");
}

最新更新