使用会话限制用户访问 - ASP.NET

Restrict user access using session - ASP.NET

我是编程新手。我开发了一个 web 应用程序,如果登录成功,我将在登录页面上捕获会话 ID,并将用户重定向到主页。

我的疑问 - 是否可以通过使用母版页中的会话控件来限制用户基于他们的角色访问网页。如果可以,如何隐藏某些网页?

登录页面代码-

con.Open();
SqlCommand cmd = new SqlCommand("select * from LoginDB where (EmpCode COLLATE Latin1_General_CS_AS = @EmpCode) and (Password COLLATE Latin1_General_CS_AS =@Password)", con);
cmd.Parameters.AddWithValue("@EmpCode", txtLogin.Text.Trim());
cmd.Parameters.AddWithValue("@Password", txtPwd.Text.Trim());
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);

if (dt.Rows.Count > 0)
{
    var userRow = dt.Rows[0];
    Session["idname"] = userRow["Name"].ToString();
    ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('" + "Login Success!" + "')</script>");
    Session["identity"] = txtLogin.Text;
    Response.Redirect("Mainpage.aspx", false);
}
else
{
    txtLogin.Text = "";
    ShowMessage("UserId / Password is Not Correct!");
}
con.Close();

要在母版页中使用的代码,

protected void Page_Load(object sender, EventArgs e)
{
   string mnm = Session["identity"].ToString();
   if (mnm == "NormalUser")
   {
       //Hide certain web pages like Asset.aspx web page
   }       
}

我建议您在 Page.OnInit 中为您拥有的每个 aspx 检查用户角色,而不是在母版页中这样做。例如在 Asset.aspx.cs 中,您可以按如下方式进行:

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);

    string mnm = Session["identity"].ToString();
    if (mnm != "NormalUser")//check whatever you want with the identity
    {
        throw new UnauthorizedAccessException("You are not allowed to view this page");
    }  
}

以便您可以将此方法应用于其他页面。