会话超时 .NET

5
我搜索了一下,但并没有找到这个问题的具体答案。在服务器端如何获取剩余的会话过期时间呢?我的会话设置如下:
// 例如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分钟点。

如何获取会话到期前的剩余时间?

3个回答

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";
} 

1

根据Drasius的方法,我编写了以下VB解决方案。

在global.asa的Session_Start中,我有以下内容--

    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" />

所以我不确定这种方法是否提供了真正与实际会话超时同步的超时。

0

如果您是服务器端,它会在任何postback时重置,因此如果您有10分钟,那么就是10分钟。客户端可以在最后一次与服务器的通信后设置一个计时器,例如,您可以设置一个8分钟的计时器,然后警告会话在2分钟后过期...当然,您希望显示实际剩余时间,而不是静态消息。

查看setTimeout方法。此链接提供了一些您可能使用的javascript定时方法的信息。


这并不能解决问题(滑动过期时间,不会将会话过期时间设置为起始点(10分钟),而是添加了“一些时间”)。但是当会话剩余时间少于一半且用户执行某些操作时,我得到的值是600秒,但它并不等于剩余会话时间,因为“slidingExpiration”添加了一些时间(我不知道有多少),但没有将会话剩余时间重置为起始的10分钟点。 - Drasius

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接