延长或控制Session的有效期的方法总结

本文介绍了四种有效的方法来延长Session的有效时间,包括使用JavaScript、JQuery、MetaRefresh和ASP.NET AJAX等技术手段,以确保用户在进行长时间操作时不会因Session过期而丢失数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果访问者在Session的设定的失效时间内(比如默认的20分钟)没有任何动作,Session就会失效,这个就意味着与Session存贮相关的变量也会同时失效,不能再访问。有时候我们需要保持Session很长的时间来等待用户完成工作,比如博客,当用户在写完文章之后提交却发现Session已经失效,这是一件多么悲惨的事情。

 

很多人可能尝试这样做

<system.web>
      <authentication mode="Forms">
        <forms timeout="60"/>
      </authentication>

    ...
    </system.web>

尽管我们可以很简单的增加Session的过期时间,但是这并不是一个很好的方案。当用户真的离开的时候,它会让你的服务器系统浪费很多内存资源来保存一些完全没有意义的东西。如果这个网站的访问量非常大的时候,可能由于Session占用的内存太多,而使你的网站运行得很慢。解决方案我们可以采用客户端周期性请求服务器的方法来保持Session。很多大型网站都是采用这样的方法,例如网易,51博客和QQ在写邮件和发文章的时候。为了达到这样的效果,我们可以使用javascript,jquery,metarefresh和asp.net ajax几种方法来解决。

1.    用javascript来保持Session

    Asp.net 仅仅会记住用户的最后一次请求,它不知道用户是否关闭了浏览器,或者是否在干别的事情。为了保住那些还开着我们的网页的用户的Session,我们可以使用JS的setInterval功能

    代码
    复制代码
       
       
    <%--
    In
    this example, image will be used to keep session alive,
    By changing image
    ' s src parameter, we ' ll make periodical requests
    to web server.
    --%>
    < img id = " imgSessionAlive " width = " 1 " height = " 1 " / >


    < script type = " text/javascript " >
    // Helper variable used to prevent caching on some browsers
    var counter;
    counter
    = 0 ;

    function KeepSessionAlive() {
    // Increase counter value, so we'll always get unique URL
    counter ++ ;

    // Gets reference of image
    var img = document.getElementById( " imgSessionAlive " );

    // Set new src value, which will cause request to server, so
    // session will stay alive
    img.src = " http://YourWebSiteUrl.com/RefreshSessionState.aspx?c= " + counter;

    // Schedule new call of KeepSessionAlive function after 60 seconds
    setTimeout(KeepSessionAlive, 60000 );
    }

    // Run function for a first time
    KeepSessionAlive();
    < / script>
    复制代码

     

     

    在这个例子里,RefreshSessionState.aspx这个页面将会每分钟被请求一次。我们通过操作SRC来请求服务器。当然这只是一个巧妙的方法,你可以使用Http Request.当然那更加的麻烦。如果你只是想保住Session的话你可以设置为19分钟(19*60*1000=1140000)。当访问的间隔很小时,比如例子的一分钟,这样做的好处是你可以准确的知道用户的离开时间,并且立即释放掉不需要使用的资源。你甚至可以把Session的过期时间定为2分钟。这样你的服务器就只会保存当前停留在你网站的用户的Session.

    因为RefreshSessionState.aspx页面会被每分钟请求,所以我们可以使用ASP.NET服务器技术来追踪我们的用户,例如统计当前用户数,用户在看那一个页面等等详细信息,如果是做一个社区性质的网站的话,相信这些会让你的网站绽放光彩的。

    2.      使用JQUERY 保持Session

    我们可以使用Jquery框架来完成相同的任务。这里我们使用Post提交方式来保持我们的Session

    代码
    复制代码
       
       
    < script language = " javascript " type = " text/javascript " src = " http://code.jquery.com/jquery-latest.js " >< / script>
    < script language = " javascript " type = " text/javascript " >

    function KeepSessionAlive() {
    // 1. Make request to server
    $.post( " http://YourWebSiteUrl.com/RefreshSessionState.aspx " );

    // 2. Schedule new request after 60000 miliseconds (1 minute)
    setInterval(KeepSessionAlive, 60000 );
    }

    // Initial call of function
    KeepSessionAlive(); Â
    < / script>
    复制代码

     

     

    Jquery的简洁性是不是让你眼红呢?

    3.      使用Meta Refresh来保持Session

    一般我们不会用refresh来定时刷新我们的整个页面,因为这会造成你的页面一闪一闪,这可不是一闪一闪亮晶晶,你要是一闪一闪的用户早跑了。所以我们一般使用一个Iframe来完成这个功能

                 <iframe height="0" width="0" src="RefreshSessionState.aspx" frameborder="0" />

                此时RefreshSessionState.aspx如果你不要跟踪用户的话不需要服务器代码。我习惯于这样写

     

               代码
    复制代码
       
       
    <% @ Page Language = " C# " %>
    < html >
    < head >
    <%
    Response.Write(
    @" <meta http-equiv=""refresh"" content=""900;url=RefreshSessionState.aspx?x= " +
    Server.UrlEncode(DateTime.Now.ToString())
    + @" "" /> " );
    %>
    </ head >
    < body >

    </ body >
    </ html >
    复制代码

    参数x的作用是为了避免浏览器缓存整个页面导致我们需要的功能成为泡影,这样我们就通过了一个iframe来完成了我们需要的功能。

    4.   使用asp.net ajax 来保持Session

    Aspx页面的代码如下:

    复制代码
                   代码
       
       
    <% @ Page Language = " C# " AutoEventWireup = " true " CodeFile = " Ajax-Refresh.aspx.cs " Inherits = " Ajax_Refresh " %>

    <! DOCTYPE html PUBLIC " -//W3C//DTD XHTML 1.0 Transitional//EN " " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd " >

    < html xmlns = " http://www.w3.org/1999/xhtml " >
    < head runat = " server " >
    < title ></ title >
    </ head >
    < body >
    < form id = " form1 " runat = " server " >
    < asp:ScriptManager ID = " ScriptManager1 " runat = " server " >
    </ asp:ScriptManager >
    < div >

    < asp:UpdatePanel ID = " UpdatePanel1 " runat = " server " >
    < ContentTemplate >
    < asp:Timer ID = " Timer1 " runat = " server " Interval = " 10000 " ontick = " Timer1_Tick " >
    </ asp:Timer >
    < asp:Label ID = " Label1 " runat = " server " Text = " Label " ></ asp:Label >
    </ ContentTemplate >
    </ asp:UpdatePanel >

    </ div >
    </ form >
    </ body >
    </ html >
    复制代码

     

    Timer控件的Interval可是设置间隔时间但是是毫秒。服务器端的代码我们可以这样写:

                  代码
    复制代码
       
       
    [ C# ]

    using System;

    public partial class Ajax_Refresh : System.Web.UI.Page
    {
    protected void Page_Load( object sender, EventArgs e)
    {
    // Set session timeout to small value, in this case
    // 2 minutes, to see quickly if Timer will keep session alive
    Session.Timeout = 2 ;
    // Set some value in session
    Session[ " Testing " ] = " session is alive " ;
    }

    // Timer will make request to server in regular time intervals
    protected void Timer1_Tick( object sender, EventArgs e)
    {
    // Write current session value into label
    Label1.Text = ( string )Session[ " Testing " ];
    Label1.Text
    += " <br /> Last request at " + DateTime.Now.ToString();
    }
    }

    [ VB.NET ]

    Partial Class Ajax_Refresh
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    ' Set session timeout to small value, in this case
    ' 2 minutes, to see quickly if Timer will keep session alive
    Session.Timeout = 2
    ' Set some value in session
    Session( " Testing " ) = " session is alive "
    End Sub

    ' Timer will make request to server in regular time intervals
    Protected Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    ' Write current session value into label
    Label1.Text = Session( " Testing " )
    Label1.Text
    &= " <br /> Last postback at " & DateTime.Now.ToString()
    End Sub
    End Class
    复制代码

    实际上在许多公司使用asp.netajax的比较少,但是如果是一些要求快速开发的项目来说,asp.net ajax也不愧为一个很好的选择。

    以上就是保持延长Session的四种解决方案,希望对你有些帮助。


    笔者测试:笔者直接使用的是第二种方法。目前测试还是很有效的。

    ### 如何延长 Token 有效期 为了确保安全性和用户体验,在设计 API 认证机制时,合理管理 Token 的生命周期至关重要。对于不同类型的 Token(如 JWT 基于 Session 的 Token),存在多种策略来实现有效期限的扩展。 #### 对于 JSON Web Tokens (JWT) 由于 JWT 是自包含型令牌,其过期时间通常编码在 Payload 中的一个特定字段 `exp` 内[^1]。要改变这一行为并允许刷新延长已签发 JWT 的寿命,可采用如下方案: - **引入 Refresh Token**:创建一对短期有效的 Access Token 和长期有效的 Refresh Token 组合。当 Access Token 到期时,客户端可以通过提供 Refresh Token 请求新的 Access Token 而无需重新登录认证过程[^3]。 ```json { "access_token": "<short-lived-jwt>", "refresh_token": "<long-lived-refresh-token>" } ``` - **滑动窗口模式**:每当用户发起请求携带未到期的 JWT 时,服务端可以选择性地更新该 JWT 的过期时间至当前时刻加上固定间隔,从而动态调整存活周期[^2]。 ```java // 假设这是 Java 实现的一部分逻辑片段 if (!isExpired(jwt)) { // 更新 token 过期时间为现在加一个小时 Claims claims = Jwts.parser().parseClaimsJws(jwt).getBody(); Date newExpirationTime = new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1)); String refreshedJwt = Jwts.builder() .setClaims(claims) .setExpiration(newExpirationTime) .signWith(SignatureAlgorithm.HS256, secretKey) .compact(); response.setHeader("Authorization", "Bearer " + refreshedJwt); } ``` #### 使用 Redis 存储 Session-based Token 另一种常见做法是在服务器端利用缓存数据库比如 Redis 来维护会话数据,并通过设定键值对的有效期达到控制目的[^4]。这种方式下,即使原始 Token 已经过期,只要对应的 Redis 键仍然存在,则认为用户的会话依然活跃。 ```python import uuid from datetime import timedelta from redis import Redis def create_session(redis_client: Redis, user_info): session_id = str(uuid.uuid4()) # 设置 session 数据及其 TTL (生存时间),例如一天 redis_client.setex(session_id, timedelta(days=1), value=user_info) return {"token": session_id} def extend_session_lifetime(redis_client: Redis, session_id): if redis_client.exists(session_id): # 将现有 session 的 TTL 扩展为额外两天 redis_client.expire(session_id, time=timedelta(days=2)) return True return False ``` 上述两种方式各有优劣,具体选择取决于应用场景的安全需求和技术栈特性。值得注意的是,无论采取哪种手段,都应该遵循最小权限原则以及定期审查和优化安全性措施。
    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值