65.9K
CodeProject 正在变化。 阅读更多。
Home

在 ASP.NET 中会话超时时重定向到另一个页面(当页面包含 Ajax UpdatePanel 时)

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.88/5 (22投票s)

2008 年 6 月 18 日

CPOL
viewsIcon

247298

在使用 Ajax UpdatePanel 进行会话超时时的一个小解决方案。

引言

ASP.NET 中的会话超时是 Web 开发人员面临的一个重要问题。当会话结束时,我们会遇到一些异常情况。互联网上也有很多解决方案来处理这个问题。但很少有讨论在会话超时时重定向到另一个页面,尤其是在使用 Ajax UpdatePanel 时。

因此,我建议一种方法来做到这一点。

解决方案

我的主要想法是:在会话结束前 3 分钟,我们会提醒用户保存数据或进行任何回发。如果用户仍然没有采取任何操作,那么在会话结束前 5 毫秒,我们会将页面重定向到 Login.aspx(或者通过重定向到自身来刷新页面)。

Using the Code

将以下代码添加到您的母版页

private void CheckSessionTimeout()
{
    string msgSession = 'Warning: Within next 3 minutes, if you do not do anything, '+
               ' our system will redirect to the login page. Please save changed data.';
    //time to remind, 3 minutes before session ends
    int int_MilliSecondsTimeReminder = (this.Session.Timeout * 60000) - 3 * 60000; 
    //time to redirect, 5 milliseconds before session ends
    int int_MilliSecondsTimeOut = (this.Session.Timeout * 60000) - 5; 

    string str_Script = @"
            var myTimeReminder, myTimeOut; 
            clearTimeout(myTimeReminder); 
            clearTimeout(myTimeOut); " +
            "var sessionTimeReminder = " + 
		int_MilliSecondsTimeReminder.ToString() + "; " +
            "var sessionTimeout = " + int_MilliSecondsTimeOut.ToString() + ";" +
            "function doReminder(){ alert('" + msgSession + "'); }" +
            "function doRedirect(){ window.location.href='login.aspx'; }" + @"
            myTimeReminder=setTimeout('doReminder()', sessionTimeReminder); 
            myTimeOut=setTimeout('doRedirect()', sessionTimeout); ";

     ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), 
           "CheckSessionOut", str_Script, true);
}
private void Page_Load(object sender, System.EventArgs e)
{
    this.CheckSessionTimeout();
}

如果您不想重定向到登录页面,只需将页面替换为以下代码即可刷新页面

function doRedirect(){ window.location.href=window.location.href; }

如果您不使用 ScriptManager,可以用 Page.RegisterClientScriptBlock(...) 替换

希望这有所帮助。

历史

  • 2008 年 6 月 18 日:初始发布
© . All rights reserved.