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