C# 如何使用角色验证密码并将管理员重定向到管理员页面和用户重定向到用户页面?
这是我的代码:C# 如何使用角色验证密码并将管理员重定向到管理员页面和用户重定向到用户页面?,c#,html,visual-studio,C#,Html,Visual Studio,这是我的代码: protected void loginBtn_Click(object sender, EventArgs e) { if (IsPostBack) { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["userDatabaseConnectionString1"].ConnectionString); conn.Open(
protected void loginBtn_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["userDatabaseConnectionString1"].ConnectionString);
conn.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("select role from accounts", conn);
SqlDataAdapter da = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
string role = Convert.ToString(ds.Tables[0].Rows[0]["role"]);
if (role == "a")
{
Response.Redirect("AdminPage/adminAccount.aspx");
}
if (role == "u")
{
Response.Redirect("UserPage/userAccount.aspx");
}
}
else
{
//record is not in ur table
}
}
}
角色a
用于管理员,角色u
用于用户
如何验证和重定向正确登录的用户
现在,无论用户名和密码是否正确,只要我单击“登录”,此代码就会将我重定向到管理员主页
我需要添加什么来修复此问题?您的密码和用户名字符串在哪里?您如何检查用户输入的内容是否有效?当您获得它们时,您可以通过以下方式使用它们:
SqlCommand cmd = new SqlCommand("select role from accounts where username = '" + usernameString + "' and password = '" + passwordString + "'", conn);
你根本不知道自己在干什么 当我试图解释你的观点时,请讲些逻辑
SqlCommand cmd = new SqlCommand("select role from accounts", conn);
此行将返回所有用户,对吗
但是您需要特定的用户数据,所以这样写
SqlCommand cmd = new SqlCommand("select role from accounts where username='"+yourusernametextbox.text+"' and password='"+yourpassword.text+"'--", conn);
这将返回角色为admin或user的真实结果
现在给你一个建议
像这样格式化查询可能会导致sql注入,而请使用参数化查询比使用参数的其他2个查询更好的答案+1非常感谢你,这起作用了!我真的很迷茫,谢谢你!!!
SqlCommand cmd = new SqlCommand("select role from accounts where Username=@Username and Password=@Password", conn);
cmd.Parameters.AddWithValue("@Username",txtUsername.Text);
cmd.Parameters.AddWithValue("@Password",txtPassword.Text);