【发布时间】:2013-12-06 14:45:38
【问题描述】:
我的任务是向 ASP.NET 4.0 Web 窗体应用程序添加功能,以便在用户会话结束前不久警告用户,并提供继续会话或结束会话的选项。
我已经通过一个确认对话框实现了这一点,该对话框警告用户会话即将结束,并提供按“确定”继续会话或按“取消”结束会话的选项。
按“取消”后,页面将重定向到注销页面。
按下“确定”后,我在应用程序 (KeepAlive.aspx) 的空 ASPX 页面上调用 JQuery GET 请求。据我了解,当用户向页面发出请求时,ASP.NET 应该负责更新会话 - 从而重置会话超时。
但是,我发现当用户按下 OK 时,会话没有延长,所以它超时了。尽管 GET 请求显然是成功的(例如调用了回调函数)。
我用来实现此功能的代码以 JavaScript 函数的形式存在,该函数通过母版页上的 onload 事件调用 - 因此它被应用程序中的所有其他页面继承。
var intervalID;
/* Set a timeout interval based on the server timeout value (-10%) */
function setTimeoutInterval()
{
/* Session timeout warning dialog */
// Get session timeout value
var timeoutMins = "<asp:ContentPlaceHolder id='timeoutPlaceholder' runat='server'><%= Session.Timeout %></asp:ContentPlaceHolder>";
// Subtract 10% of the timeout value - to give the user a chance to continue the session before it expires
var remainingTimeMins = Math.ceil(timeoutMins * 0.1);
var timeoutMins = timeoutMins * 0.9;
// Convert the timeout value to milliseconds
var timeout = timeoutMins * 60 * 1000;
// Set javascript timeout
intervalID = window.setInterval("displayTimeoutDialog(" + remainingTimeMins + ")", timeout);
}
/* Display a dialog prompting the user to continue the current session or to end the session */
function displayTimeoutDialog(remainingTimeMins)
{
var result = confirm("The session will end in ~" + remainingTimeMins +
" minute(s). Press OK to continue, or Cancel to log out.");
if (result == true) {
// Keep the session alive
alert("Keep alive!");
$.get("KeepAlive.aspx", function() { alert("Successful request"); });
}
else {
// Redirect to the logout page
window.location.href("Logout.aspx");
}
}
【问题讨论】:
-
为什么要将 JavaScript 变量设置为 asp 服务器控件...然后将其乘以 .9?
-
@Mike 他没有将其设置为服务器控件。他的代码将呈现为:“var timeoutMins = 20”或任何设置。然后他将其乘以 0.9,以便在会话实际到期之前弹出对话框。
-
是的,cmets 解释了它。我只是从服务器获取服务器超时值(例如 20 分钟),然后设置一个间隔以在会话到期之前警告用户(20 * 0.9 = 18 分钟,因此警告将在会话前 2 分钟变为过期)。
-
@Stefan 我知道 ASP.NET 会在它到达页面之前处理它......这只是一种令人困惑的方式,并且有更简单的方法来获取服务器变量javascript。
-
另一种选择是使用文字:
并在代码隐藏中设置其值。
标签: javascript jquery asp.net session-timeout