我正在尝试使用访问数据库向我的asp.net 2013应用程序添加登录功能。如何获得多个用户角色才能访问同一页面?
这是我创建的公共静态bool
public static bool doesUserHaveRole(string username, string roleToTest)
{
string sqlStatement = "SELECT * FROM UsersTb WHERE LoginName=@LoginName";
string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
OleDbConnection oleDbConn = new OleDbConnection(connStr);
oleDbConn.Open();
OleDbCommand command = new OleDbCommand(sqlStatement, oleDbConn);
command.Parameters.AddWithValue("@LoginName", username);
OleDbDataReader dr = command.ExecuteReader();
if (dr.HasRows == false) return false;
dr.Read();
string role = dr["UserRole"].ToString();
if (role == roleToTest) return true;
return false;
}
答案 0 :(得分:1)
您可以将角色ID传递给查询,而不是为用户获取所有行并检查所有行。
您可以返回匹配行的计数:
public static bool doesUserHaveRole(string username, string roleToTest)
{
string sqlStatement = "SELECT COUNT(*) AS C FROM UsersTb WHERE LoginName=@LoginName AND UserRole=@UserRole";
string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
OleDbConnection oleDbConn = new OleDbConnection(connStr);
oleDbConn.Open();
OleDbCommand command = new OleDbCommand(sqlStatement, oleDbConn);
command.Parameters.AddWithValue("@LoginName", username);
command.Parameters.AddWithValue("@UserRole", roleToTest);
OleDbDataReader dr = command.ExecuteReader();
return dr.Read() && ((int) dr["C"]) > 0;
}