ASP.net中如何让Session永不过期

作者首先借鉴了一篇文章中所提到的定时刷新方法,把如下所示的代码放到Page_Load()事件:

private void ReconnectSession()
{
    int int_MilliSecondsTimeOut = (this.Session.Timeout * 60000) - 30000;
    string str_Script = @"
    <script type='text/javascript'>
        function Reconnect()
        {
            window.open('reconnect.aspx','reconnect','width=5,height=5,top=1800,
            left=1800,scrollbars=no,showintaskbar=no');
        }
        window.setInterval('Reconnect()',"+int_MilliSecondsTimeOut.ToString()+ @");
    </script>";
    this.Page.RegisterClientScriptBlock("Reconnect", str_Script);
}
考虑到如果项目中包含很多页面,给每个页面都拷上这样的代码也是一个力气活,作者决定新建一个类,这个类继承自System.Web.UI.Page:
public class YourNewPageClass : System.Web.UI.Page
然后改写YourNewPageClass类的OnInit()事件: override protected void OnInit(EventArgs e)
{
    base.OnInit(e);
    if (Context.Session != null)
    {
        int int_MilliSecondsTimeOut = (this.Session.Timeout * 60000) - 30000;
        string str_Script = @"
        <script type='text/javascript'> function Reconnect()
        {
            window.open('reconnect.aspx','reconnect','width=5,height=5,top=1800,
            left=1800,scrollbars=no,showintaskbar=no');
        }
            window.setInterval('Reconnect()',"+int_MilliSecondsTimeOut.ToString()+ @");
        </script>";
        this.Page.RegisterClientScriptBlock("Reconnect", str_Script);
    }
}
以后新建的页面只要继承这个类就可以实现永不过期的Session了。

更大的问题:弹出窗口被浏览器过滤掉怎么办?

作者终于想到了伟大的万精油武器—Ajax了: function getObjectHTTP()
{
    var xmlhttp = null
    if (navigator.userAgent.indexOf("MSIE")>=0)
    {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
    }
    else
    {
        xmlHttp = new XMLHttpRequest()
    }
    return xmlhttp
}

function Reconnect()
{
    var url='reconnect.aspx'
    xmlHttp=getObjectHTTP()
    xmlHttp.open('GET', url , true)
    xmlHttp.send(null)
}
看看Reconnect函数的实现,这可是Ajax实现的标准模式哦 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值