如何找出登录的用户 [英] How do I find out which user is logged in
问题描述
我有一个登录页面。有一个名为user_privilege的表和名为user_type的列。工作人员和管理员现在有两个值我想知道哪个用户已经登录,所以我们可以让他们在各自的区域。我很难搞清楚
我尝试过的事情:
I have a Login page. There is a table named user_privilege and column named user_type. There is two values in it Staff and Admin now i want to find out which user had logged in so we can let them in their respective areas. I am having hard time figuring out how
What I have tried:
protected void btnLogin_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(@"Data Source =DESKTOP-
RVF1OET\SQLEXPRESS; Initial Catalog = ClothStockManagement; Integrated
Security = True;"))
{
con.Open();
string query = "select count(1) from user_privilege where
user_id=@username and password=@password";
string userType= "select user_type from user_privilege";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@username", userNameBox.Text.Trim());
cmd.Parameters.AddWithValue("@password", passwordBox.Text.Trim());
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count == 1)
{
if (userType == "Staff")
{
messageBox.Text = "Staff";
Response.Redirect("test.aspx");
}
else
{
Session["admin"] = userNameBox.Text;
Response.Redirect("AdminDashboard.aspx");
messageBox.Text = "Ad";
}
}
else
{
messageBox.Text = "Failed";
}
}
}
推荐答案
首先,永远不要将密码存储为纯文本。请查看密码存储:如何操作。 [< a href =https://www.codeproject.com/Tips/186585/Password-Storage-How-to-do-ittarget =_ blanktitle =New Window> ^ ] br />
关于问题本身,不是计算记录,而是选择实际数据。换句话说,比如
First of all, never store the passwords as plain text. Have a look at Password Storage: How to do it.[^]
About the question itself, instead of counting the records, select the actual data. In other words something like
string query = "select user_type from user_privilege where
user_id=@username and password=@password";
然后您可以使用 SqlCommand.ExecuteReader方法(System.Data.SqlClient) [ ^ ]运行查询并调查返回的数据。
ADDITION
作为使用阅读器的一个小例子,请考虑以下内容。请注意,这不能解决密码问题。
You can then use SqlCommand.ExecuteReader Method (System.Data.SqlClient)[^] to run the query and investigate the data returned.
ADDITION
As a samll example of using a reader, consider the following. Note this doesn't fix the password problem.
...
con.Open();
string query = "select user_type from user_privilege where user_id=@username and password=@password";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@username", userNameBox.Text.Trim());
cmd.Parameters.AddWithValue("@password", passwordBox.Text.Trim());
SqlDataReader reader = command.ExecuteReader();
if !(reader.Read()) {
messageBox.Text = "User not found";
Response.Redirect("test.aspx");
} else if (reader[0].ToString() == "Staff") {
messageBox.Text = "Staff";
Response.Redirect("test.aspx");
} else {
Session["admin"] = userNameBox.Text;
Response.Redirect("AdminDashboard.aspx");
messageBox.Text = "Ad";
}
else
{
messageBox.Text = "Failed";
}
...
这篇关于如何找出登录的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!