登录表单和会话

时间:2012-10-12 09:01:28

标签: c# asp.net session login

我有一个带有两个方框的登录表单和buttonclick上的按钮我使用sql数据库验证用户并将id存储在会话中并设置FormsAuthentication供以后使用。在注销按钮上我将它们重定向到logout.aspx,在那里我销毁会话并重定向到登录页面:

 Session.Abandon();
 FormsAuthentication.SignOut();

现在退出后如果我使用浏览器返回按钮返回,我仍然可以看到我的previouse页面但是如果我刷新我得到object reference not set to an instance of an object.

protected void Page_Load(object sender, EventArgs e)
Line 33:         {
Line 34:             string id = Session["ID"].ToString();

如果发生这种情况,将用户送回登录的最佳方法是什么?

2 个答案:

答案 0 :(得分:5)

Nota:我建议您使用

if(Session["ID"] != null)
{

}

但我也建议您使用此configuration

<system.web>
  <authentication mode="Forms">
    <forms loginUrl="Login.aspx"
           defaultUrl="default.aspx" />
  </authentication>
</system.web>

您的退出链接/按钮应指向包含此代码的页面以及您想要的任何其他内容。

private void Page_Load(object sender, System.EventArgs e)
{
    // Put user code to initialize the page here
    Session.Abandon();
    FormsAuthentication.SignOut();
}

Nota:序列图

enter image description here

答案 1 :(得分:1)

首先应检查Session["ID"] != null 否则,用户未经过身份验证。

但是如果你使用FormsAuthentication,你也可以使用User.Identity.IsAuthenticated

相关问题