简体   繁体   中英

Session check deny page access ASP.NET

I have a login page that is checking users and passwords from an XML file, first I set a string that I will use with sessions then check if user exist

string roleCheck = "";

            string userName = node.SelectSingleNode("username").InnerText;
        string passWord = node.SelectSingleNode("password").InnerText;
        string isAdmin = node.SelectSingleNode("role").InnerText;

        if (isAdmin == "admin" && userName == TextBoxUsername.Text && passWord == TextBoxPassword.Text)
        {
            roleCheck = "admin";
            Session["RoleCheck"] = roleCheck;
            Response.Redirect("admin.aspx");
        }

Now here is where it fails, it seems I can access admin.aspx even without logging on, I have this in Page_Load on admin.aspx

    protected void Page_Load(object sender, EventArgs e)
{
        if (Session["RoleCheck"] == "")
        {
            Response.Redirect("login.aspx");
        }
}

Shouldnt this redirect non logged on users?

You need to check just session is null like below code. not check empty or blank.

protected void Page_Load(object sender, EventArgs e)
 {
      if (!IsPostBack)
        {
          if (Session["RoleCheck"] == null)
          {
              Response.Redirect("login.aspx");
          }
        }
  }

No, because it is checking whether Session is blank string, but here, Session is null, ie not a blank string. Hence condition fails.

You should check Session for null rather than empty string.

if(Session["RoleCheck"] == null)
{
   // redirect
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM