会话超时后重定向到登录页面

时间:2012-09-19 20:21:39

标签: asp.net .net vb.net visual-studio-2010 session-timeout

我发现了一些类似的问题,但没有人给我我真正需要的东西。

这是事情,我已将此添加到我的web.config以处理用户会话到期:

<sessionState mode="InProc" timeout="1" />

1分钟后,来自Session_End的{​​{1}}事件被提出:

Global.asax

这不起作用,因为:

Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
    Response.Redirect("Login.aspx")
End Sub

(顺便说一句,this question得到了一个问题,告诉我这没关系,并且得到了回报。)

我不想要任何幻想。我只想要一种简单的方法,在会话时间到期时将用户重定向到登录页面。就是这样。

谢谢。

4 个答案:

答案 0 :(得分:3)

描述

您可以使用Page_Init

中的global.asax事件

示例

Protected Sub Page_Init(sender As Object, e As EventArgs)
 If Context.Session IsNot Nothing Then
  If Session.IsNewSession Then
   Dim newSessionIdCookie As HttpCookie = Request.Cookies("ASP.NET_SessionId")
   If newSessionIdCookie IsNot Nothing Then
    Dim newSessionIdCookieValue As String = newSessionIdCookie.Value
    If newSessionIdCookieValue <> String.Empty Then
     ' This means Session was timed Out and New Session was started
     Response.Redirect("Login.aspx")
    End If
   End If
  End If
 End If
End Sub

更多信息

答案 1 :(得分:2)

Session_End是服务器端事件,这意味着它在Web服务器上触发,与客户端的请求无关。这就是请求不可用的原因。

在这件事上你有两个选择:

  1. 在每个客户端请求中,检查是否设置了特定的Session变量。如果不是,则表示先前的会话已过期,并且必须填充新的会话。 (我假设这就是你要检查会话到期的原因)

  2. 在客户端上进行javascript调用,定期返回服务器以检查Session是否仍然有效。如果会话已过期,您可以警告用户其会话即将过期。

  3. HTH

答案 2 :(得分:0)

检查每个Page_Init事件的过期会话。如果要检查的页面太多,我通常会这样做:

  • 我创建了一个基类,并继承自System.Web.UI.Page。
  • 在我的基类的Page_Init事件中编写我的重定向逻辑。
  • 让我的其余页面继承自此基类。
祝你好运。

答案 3 :(得分:0)

protected void Page_Init(object sender, EventArgs e)
{
    if (Context.Session != null)
    {
        if (Session.IsNewSession)
        {
            HttpCookie newSessionIdCookie = Request.Cookies["ASP.NET_SessionId"];
            if (newSessionIdCookie != null)
            {
                string newSessionIdCookieValue = newSessionIdCookie.Value;
                if (newSessionIdCookieValue != string.Empty)
                {
                    // This means Session was timed Out and New Session was started
                    Response.Redirect("Login.aspx");
                }
            }
        }
    }
}