繁体   English   中英

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

[英]I'm validating a form in C# but I don't know what I am doing wrong. Please help me solve this

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

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");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM