【问题标题】:ASP.NET, Session maintaining on pageload and postbackASP.NET,页面加载和回发时的会话维护
【发布时间】:2013-03-02 15:38:58
【问题描述】:

我正在创建一个需要维护登录用户会话的网站。有不同的页面,因此必须维护每个页面的会话。我在主页上输入按钮的单击事件中传递会话变量中的值。 该代码第一次运行良好,但是当用户从另一个页面重定向到主页时,会话变为空。我很困惑在哪里进行会话以保留所有页面的价值。?

这是我的代码:

 protected void Page_Load(object sender, EventArgs e)
{
    //Session["UserName"] = null;
    //Session["UserRoles"] = null;
    if (!Page.IsPostBack) //if page is not postback then here
    {
        Session["UserName"] = null;
        Session["UserRoles"] = null;
        if (Session["UserRoles"] != null && (String)Session["UserRoles"] == "Admin")
        {
            divLoggedInMember.Visible = true;
            lblLoggedinUser.Text = "Welcome" + " " + Session["UserName"] + "(Admin)";
        }
        else if (Session["UserRoles"] != null && (String)Session["UserRoles"] == "member")
        {
            divLoggedInMember.Visible = true;
            lblLoggedinUser.Text = "Welcome" + " " + Session["UserName"];
        }
    }

    else //if page postback then here
    {
        if (Session["UserRoles"] != null)
        {
            if ((String)Session["UserRoles"]=="Admin")
            {
                divLoggedInMember.Visible = true;
                lblLoggedinUser.Text = "Welcome" + " " + Session["UserName"] + "(Admin)";
            }
            else
            {
                divLoggedInMember.Visible = true;
                lblLoggedinUser.Text = "Welcome" + " " + Session["UserName"];
            }
        }
    }


}


 protected void btnenter_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            Session["UserName"] = null;
            Session["UserRoles"] = null;
            DataTable dt = new DataTable();
            dt=getUserInfo(txtUserId.Text.Trim(),txtPassword.Text.Trim());

            if (dt.Rows.Count == 0)
            {
                Response.Write("<script> alert('User Not Exist')</script>");
            }
            else
            {
                strUserName = dt.Rows[0]["User_Name"].ToString();
               // strUserName = txtUserId.Text.Trim(); 
                struserRoles = dt.Rows[0]["USER_ROLE"].ToString();
                Session["UserName"] = (String)strUserName;
                Session["UserRoles"] = (String)struserRoles;

                if (Session["UserRoles"] != null && (String)Session["UserRoles"]=="Admin")
                {
                    divLoggedInMember.Visible = true;
                    lblLoggedinUser.Text = "Welcome" + " " + Session["UserName"] + "(Admin)";
                }
                else if (Session["UserRoles"] != null && (String)Session["UserRoles"] == "Member")
                {
                    divLoggedInMember.Visible = true;
                    lblLoggedinUser.Text = "Welcome" + " " + Session["UserName"];
                }
                Response.Redirect("MemberPage.aspx", false);
            }
        }
        catch (Exception ex)
        {
            ex.Message.ToString();
        }
    }

【问题讨论】:

  • 根据您的问题,我不太确定您是否了解会话行为在 ASP.NET 中的工作原理。您不必做任何事情来保持同一网站中页面之间的会话。
  • 嗨大卫,谢谢你的回复,我是 ASP.Net 的初学者,所以我要求你对我放轻松,但我知道会话是在 ASP.Net 中维护的,实际上我需要知道我应该在哪里检查我的会话变量,以便区分管理员或会员用户并维护该会话值?
  • 没问题!实际上,我认为@Hussein Roncevic 的回答非常好 - ASP.NET 可以为您管理大部分此类内务管理,并且它将使您的代码更易于维护。

标签: asp.net session pageload


【解决方案1】:

您遇到的问题是,在第一个if 部分中,当您检查 PostBack 时,您正在清除 Session 变量,然后检查它们是否为空。这里没有意义。它们将始终为空,您的 if 和 else if 将永远不会发生。重新考虑您的策略以及您想要实现的目标。

现在,我的 cmets 关于您要做什么...首先,以这种方式使用 Session 是您在 Classic ASP 中会做的事情。使用 ASP.NET 有更好的机制来做到这一点。相反,您应该利用MembershipProvider 和RoleProvider 来验证您的用户并跟踪他们。您通常不会从会话变量中读取用户名,而是使用Page.User.Identity.Name 来检索用户的 ID 或用户名。除此之外,您还可以在Roles 类中使用Roles.IsUserInRole() 或其他一些静态方法。

第二件事,你重复你的变量名太多次了。也就是说,您正在使用硬编码的字符串,这些字符串在太多地方指向同一事物。您的维护将一团糟。当您仍处于开发阶段的早期时,请切换到 FormsAuthentication 让 ASP.NET 为您处理上述所有任务。

更新:ASP.NET 包含一组有关登录和安全的组件。其中之一是LoginView,它允许根据不同的角色指定不同的视图。通过使用此控件,您不必为正在执行的检查而烦恼。

您在 Page_Load 中所做的检查是可以的,但您确实需要对此进行优化。如果需要经常检查,请不要打扰if (IsPostBack) ... else ...。在外面做这个检查。例如:

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["UserRoles"] != null && Session["UserRoles"] == "Admin")
    {
        // Show Admin section
        // Hide Non-admin section
    }
    else
    {
        // Hide Admin section
        // Show non-admin section
    }

    if (!IsPostBack)
    {
        // Do Postback logic here
    }
}

同样,您想要实现的目标已经可以作为LoginView 组件使用。看看这些Web Forms tutorials on ASP.NET

【讨论】:

  • 感谢侯赛因的回复,
  • 感谢 Husein 的回复,实际上我需要为管理员维护会话,为成员维护会话,并且基于这些角色,我需要显示/隐藏一些元素,这就是为什么我正在制作会话并维护它们。是的,我明白了在第一个 if 语句中分配空值的意义。你能告诉我究竟在哪里使用这个会话,以便检查登录用户是管理员还是会员?提前致谢
【解决方案2】:

根据您的问题,我不太确定您是否了解会话行为在 ASP.NET 中的工作原理。您不必做任何事情来保持同一网站中页面之间的会话。此外,您提供的代码 sn-p 将永远不会做任何事情:

       // You set theses two session vars to null, but then 
       // immediately check for contents??
       Session["UserName"] = null;
        Session["UserRoles"] = null;

        // Neither of these if statements will ever evaluate to true,
        // because you just set them to null above..
        if (Session["UserRoles"] != null && (String)Session["UserRoles"] == "Admin")
        {
            divLoggedInMember.Visible = true;
            lblLoggedinUser.Text = "Welcome" + " " + Session["UserName"] + "(Admin)";
        }
        else if (Session["UserRoles"] != null && (String)Session["UserRoles"] == "member")
        {
            divLoggedInMember.Visible = true;
            lblLoggedinUser.Text = "Welcome" + " " + Session["UserName"];
        }

【讨论】:

    猜你喜欢
    • 2014-03-07
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多