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

如果访问者在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的四种解决方案,希望对你有些帮助。


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

    • 0
      点赞
    • 7
      收藏
      觉得还不错? 一键收藏
    • 0
      评论

    “相关推荐”对你有帮助么?

    • 非常没帮助
    • 没帮助
    • 一般
    • 有帮助
    • 非常有帮助
    提交
    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

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

    抵扣说明:

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

    余额充值