检查会话是否超时

kra*_*626 5 asp.net session timeout

这是我除 EndSession.aspx 之外的所有页面的基类

override protected void OnInit(EventArgs e)  {  
base.OnInit(e);  

if (Context.Session != null)  
     {  
         //check the IsNewSession value, this will tell us if the session has been reset.  
         //IsNewSession will also let us know if the users session has timed out  
         if (Session.IsNewSession)  
         {  
            //now we know it's a new session, so we check to see if a cookie is present  
             string cookie = Request.Headers["Cookie"];  
             //now we determine if there is a cookie does it contains what we're looking for 
             if ((null != cookie) && (cookie.IndexOf("ASP.NET_SessionId") >= 0) )//&& !Request.QueryString["timeout"].ToString().Equals("yes"))  
             {  
                 //since it's a new session but a ASP.Net cookie exist we know  
                 //the session has expired so we need to redirect them  

                 Response.Redirect("EndSession.aspx?timeout=yes");  
             }  
         }  
     }  
 } 
Run Code Online (Sandbox Code Playgroud)

但在 EndSession 上,我尝试导航回 default.aspx,然后上面的代码只是重定向回 EndSession.aspx。

因此,为了更好地说明:第 1 步:转到 mypage.aspx 第 2 步:等待超时第 3 步:尝试导航离开第 4 步:重定向到 EndSession.aspx 第 5 步:尝试导航离开第 6 步:转到设置 4

Setp 6 实际上应该能够导航离开......

(如有需要请要求进一步说明)

有任何想法吗?

谢谢!!!

kra*_*626 4

我摆脱了原来的底页。

将其放入 Global.asax 的 Session_Start 中

void Session_Start(object sender, EventArgs e) 
{
    string cookie = Request.Headers["Cookie"];
    // Code that runs when a new session is started
    if ((null != cookie) && (cookie.IndexOf("ASP.NET_SessionId") >= 0))//&& !Request.QueryString["timeout"].ToString().Equals("yes"))  
    {
        if(Request.QueryString["timeout"] == null || !Request.QueryString["timeout"].ToString().Equals("yes"))
            Response.Redirect("Default.aspx?timeout=yes");
    }
}
Run Code Online (Sandbox Code Playgroud)

将其放在 Defualt.aspx 页面上:

 if (!IsPostBack)
    {
        if (Request.QueryString["timeout"] != null && Request.QueryString["timeout"].ToString().Equals("yes"))
        {
            Response.Write("<script>" +
               "alert('Your Session has Timedout due to Inactivity');" +
               "location.href='Default.aspx';" +
               "</script>");
        }
    }
Run Code Online (Sandbox Code Playgroud)

即使 Default.aspx 页面发生超时,此解决方案也有效

我使用的解决方案的讨论发布在此处:How to stop basepage from recursivlyDetecting session timeout