2013-02-22 153 views
5

我搜索了但我没有找到这个问题的任何具体答案。 如何在服务器中获得价值在会话到期之前剩余多少时间? 我的会话设置:会话超时.NET

//超时例如10分钟。

<authentication mode="Forms"> <forms name=".ASPXAUTH_External" loginUrl="Authentication/Unauthorized.aspx" protection="All" timeout="10" path="/" slidingExpiration="true" defaultUrl="~/Pages/home.aspx" cookieless="UseDeviceProfile" enableCrossAppRedirects="false"/> 
</authentication> 
<sessionState mode="InProc" timeout="10"> 
</sessionState> 

我得到的初始值(它会得到10 * 60 = 600秒):

SessionStateSection sessionSection = (SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState"); 
countdown.Text = sessionSection.Timeout.TotalSeconds.ToString(); 

但是,当会话时间离开不到一半的用户做一些动作。我得到初始值600,但它左边的会话时间不相等,因为“slidingExpiration”增加了一些时间(我不知道多少),但不会重置会话剩余时间,以开始10分钟点。

如何获得剩余会话时间直至到期?

回答

2

我发现会话过期的那段时间,我可以得到像这样:

DateTime dateNow = DateTime.Now; 
if (HttpContext.Current.User.Identity is FormsIdentity) 
{ 
    HttpCookie authCookie = this.Context.Request.Cookies[FormsAuthentication.FormsCookieName]; 
    FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); 
    double leftSeconds = (authTicket.Expiration - dateNow).TotalSeconds; 
    // Control in MasterPage, where I setting value ant then taking for JavaSript to CountDown message 
    countdown.Text = leftSeconds > 0 ? leftSeconds.ToString() : "0"; 
} 
0

如果你是服务器端,它将被重置(任何回发),所以如果你有10分钟,它是10分钟。客户端可以在最后一次访问服务器之后设置一个计时器,例如,您可以设置一个8分钟计时器,然后警告该会话在2分钟内过期。当然,您希望显示剩余的实际时间,而不是静态的信息。

看看setTimeout方法。 This link有关于您可能使用的一些javascript计时方法的信息。

+0

这个。没有解决问题(滑动过期,不设置会话过期到开始点(10分钟)它添加“一段时间”)。但是,当会话时间剩下不到一半,用户做一些行动。我获得了600秒的价值,但对于左侧会话时间并不相等,因为“slidingExpiration”增加了一些时间(我不知道有多少时间),但不会将会话剩余时间重置为开始10分钟点。 – Drasius 2013-02-23 08:20:47

0

继Drasius的方法,我编写了一个VB解决方案如下。

在上在session_start的global.asa我有 -

Session("sessStart") = DateTime.Now 
    Session("TO") = Session.Timeout 

在页面主文件我有 -

Dim timemsg As String = "" 
    Dim sstrt As DateTime = Session("sessStart") 
    timemsg = "Strt=" & sstrt.ToShortTimeString() & " TO=" & Session("TO") & "<br />" 
    Dim datenow = DateTime.Now 
    Dim cusrn = HttpContext.Current.User.Identity.Name 
    If cusrn <> "" Then 
     Dim authcookie As System.Web.HttpCookie 
     authcookie = HttpContext.Current.Request.Cookies(FormsAuthentication.FormsCookieName) 
     Dim authTicket As System.Web.Security.FormsAuthenticationTicket 
     authTicket = FormsAuthentication.Decrypt(authcookie.Value) 
     Dim leftminutes = (authTicket.Expiration - datenow).TotalMinutes 
     timemsg &= "Remain: " 
     If leftminutes > 0 Then 
      timemsg &= leftminutes.ToString("F1") & " mins" 
     Else 
      timemsg &= "0 mins" 
     End If 
    End If 
    lblShowTime.Text = timemsg 

这个工作的方式之后 - 当我刷新页面,我得到降低超时时间。然而,剩下的总是初始时间显示30分钟后,即使我有web.config中设置如下:

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

所以我不那么肯定,这种做法是给那真的与实际同步超时会话超时。