0

我在 Visual Studio 2010 中开发了一个 Web 应用程序,并试图向该应用程序添加一个用户登录系统。到目前为止,我无法验证用户密码,因为程序告诉我所有密码都不正确,即使它与与该用户名关联的密码匹配。这是我给儿子写的代码:

    protected void n_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        con.Open();
        string cmdStr = "select count(*) from Registration where UserName='" + TextBoxUserName.Text + "'";
        SqlCommand CheckUser = new SqlCommand(cmdStr, con);
        int Temp = Convert.ToInt32(CheckUser.ExecuteScalar().ToString());
        if (Temp == 1)
        {
            string cmdStr2 = "Select Password from Registration where UserName ='" + TextBoxUserName.Text + "'";
            SqlCommand pass = new SqlCommand(cmdStr2, con);
            string password = pass.ExecuteScalar().ToString();
            con.Close();

            if (password == TextBoxPassword.Text)
            {
                Session["New"] = TextBoxUserName.Text;
                Response.Redirect("HomePage.aspx");
            }
            else
            {
                Label1.Visible = true;
                Label1.Text = "Password is invalid";
            }
        }
        else
        {
             Label1.Visible = true;
             Label1.Text = "Username is invalid";
        }


    }
}

}

无论输入什么密码,程序都会输出“密码无效”,这表明问题出在 if 语句的第一部分?或者它使用的变量?可能还值得一提的是,无效的用户名会以同样的方式标记出来,这很好用。

提前致谢 :)

4

2 回答 2

1

请改用ASP.NET 身份验证

于 2012-04-30T17:11:27.647 回答
1

你正在做的事情对于它应该做的事情来说似乎太复杂了..

编辑:在用户评论后我编辑了我的答案:

 public bool Login(String uName, String pasw)
{
    using (SqlConnection myConnection = new SqlConnection(connString))
    {
        string oString = "Select ID from yourTable where username = @username AND paswoord = @password";
        SqlCommand oCmd = new SqlCommand(oString, myConnection);
        oCmd.Parameters.AddWithValue("@username", uName);
        oCmd.Parameters.AddWithValue("@password", pasw);
        string id = null;
        myConnection.Open();
        using (SqlDataReader oReader = oCmd.ExecuteReader())
        {              
            while (oReader.Read())
            {
                id = oReader["id"].ToString();
            }
            myConnection.Close();
        }
        if (id == null)
        {
            return false;
        }
        else
        {
            return true;
        }         
    }
}

你可以尝试这样的事情。此外,它可能与它无关,但是当您将属性命名为“密码”时,某些数据库不喜欢它,您可以尝试将其更改为“pw”或“pasw”或其他。

于 2012-04-30T18:03:39.920 回答