我有一个asp.net网站,我需要在会话达到超时时发生弹出/层/警报(比方说10分钟)。弹出窗口将说明您的帐户会话将由于不活动而显示,并且有一个用于继续会话的按钮或一个用于注销的按钮。
我在网上看到了不同的方法,但处理这个问题的最佳/正确方法是什么?如果弹出窗口打开的时间过长,我是否需要额外超时?
答案 0 :(得分:23)
查看这篇文章,其中包含了您的需求所需的所有内容
Alert Session Time out in ASP.NET
<script language="javascript" type="text/javascript">
var sessionTimeoutWarning =
"<%= System.Configuration.ConfigurationSettings.AppSettings
["SessionWarning"].ToString()%>";
var sessionTimeout = "<%= Session.Timeout %>";
var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
setTimeout('SessionWarning()', sTimeout);
function SessionWarning() {
var message = "Your session will expire in another " +
(parseInt(sessionTimeout) - parseInt(sessionTimeoutWarning)) +
" mins! Please Save the data before the session expires";
alert(message);
}
</script>
答案 1 :(得分:5)
之前已经解决了这个问题,例如: ASP.NET - Javascript timeOut Warning based on sessionState timeOut in web.config
但是,AFAIK没有一种完全可靠的方法可以做到这一点,因为:
答案 2 :(得分:1)
下面是一些带有jQuery的JavaScript,用于警告用户ASP.NET Forms Authentication超时,如果达到超时,则会将它们重定向到登录页面。它也可以改进并适应会话超时。它还将通过&#34; pinging&#34;重置身份验证超时。用户通过单击,键入或调整大小与页面交互时的服务器。
请注意,这确实通过每次点击,按键,调整大小来增加服务器的负载,但它非常小。尽管如此,如果您有许多用户输入,您将需要评估影响。我无法想到另一种方法,因为服务器必须参与,因为超时即将到期。
另请注意,JS中的超时不是硬编码的。它从服务器获得超时,因此您只需将其保存在Web.config中的一个位置。
(function ($, undefined) {
if (!window.session) {
window.session = {
monitorAuthenticationTimeout: function (redirectUrl, pingUrl, warningDuration, cushion) {
// If params not specified, use defaults.
redirectUrl = redirectUrl || "~/Account/Login";
pingUrl = pingUrl || "~/Account/Ping";
warningDuration = warningDuration || 45000;
cushion = cushion || 4000;
var timeoutStartTime,
timeout,
timer,
popup,
countdown,
pinging;
var updateCountDown = function () {
var secondsRemaining = Math.floor((timeout - ((new Date()).getTime() - timeoutStartTime)) / 1000),
min = Math.floor(secondsRemaining / 60),
sec = secondsRemaining % 60;
countdown.text((min > 0 ? min + ":" : "") + (sec < 10 ? "0" + sec : sec));
// If timeout hasn't expired, continue countdown.
if (secondsRemaining > 0) {
timer = window.setTimeout(updateCountDown, 1000);
}
// Else redirect to login.
else {
window.location = redirectUrl;
}
};
var showWarning = function () {
if (!popup) {
popup = $(
"<div style=\"text-align:center; padding:2em; color: black; font-color: black; background-color:white; border:2px solid red; position:absolute; left: 50%; top:50%; width:300px; height:120px; margin-left:-150px; margin-top:-90px\">" +
"<span style=\"font-size:1.4em; font-weight:bold;\">INACTIVITY ALERT!</span><br/><br/>" +
"You will be automatically logged off.<br/><br/>" +
"<span style=\"font-size:1.4em; font-weight:bold;\" id=\"countDown\"></span><br/><br/>" +
"Click anywhere on the page to continue working." +
"</div>")
.appendTo($("body"));
countdown = popup.find("#countDown");
}
popup.show();
updateCountDown();
};
var resetTimeout = function () {
// Reset timeout by "pinging" server.
if (!pinging) {
pinging = true;
var pingTime = (new Date()).getTime();
$.ajax({
type: "GET",
dataType: "json",
url: pingUrl,
}).success(function (result) {
// Stop countdown.
window.clearTimeout(timer);
if (popup) {
popup.hide();
}
// Subract time it took to do the ping from
// the returned timeout and a little bit of
// cushion so that client will be logged out
// just before timeout has expired.
timeoutStartTime = (new Date()).getTime();
timeout = result.timeout - (timeoutStartTime - pingTime) - cushion;
// Start warning timer.
timer = window.setTimeout(showWarning, timeout - warningDuration);
pinging = false;
});
}
};
// If user interacts with browser, reset timeout.
$(document).on("mousedown mouseup keydown keyup", "", resetTimeout);
$(window).resize(resetTimeout);
// Start fresh by reseting timeout.
resetTimeout();
},
};
}
})(jQuery);
只需在页面加载时调用以上内容:
window.session.monitorAuthenticationTimeout(
"/Account/Login", // You could also use "@FormsAuthentication.LoginUrl" in Razor.
"/Account/Ping");
在服务器上,您需要一个返回剩余时间的操作。您也可以添加更多信息。
public JsonResult Ping()
{
return Json(new {
timeout = FormsAuthentication.Timeout.TotalMilliseconds
},
JsonRequestBehavior.AllowGet);
}
答案 3 :(得分:1)
我去看了post的Pranay Rana中的文章,我喜欢一般的想法,但是代码可以使用一些简化的方法。这是我的版本。对于平板电脑/移动设备问题,请参见以下内容:
<script language="javascript" type="text/javascript">
var minutesForWarning = 4;
var sessionTimeout = parseInt("@Session.Timeout"); // razor syntax, otherwise use <%= Session.Timeout %>
var showWarning = true;
function SessionWarning() {
showWarning = false;
alert("Your session will expire in " + minutesForWarning + " mins! Please refresh page to continue working.");
// leave a second for redirection fct to be called if expired in the meantime
setTimeout(function () { showWarning = true; }, 1000);
}
function RedirectToWelcomePage() {
if (showWarning)
alert("Session expired. You will be redirected to welcome page.");
document.getElementById('logoutForm').submit();
// window.location = "../Welcome.aspx"; // alternatively use window.location to change page
}
setTimeout('SessionWarning()', (sessionTimeout - minutesForWarning) * 60 * 1000);
setTimeout('RedirectToWelcomePage()', sessionTimeout * 60 * 1000);
</script>
好吧,在平板电脑或手机上,您不能指望setTimeout,因为当设备锁定或浏览器未激活时,javascript的执行会暂停。相反,我正在进行定期检查(就我而言,我认为每10秒钟就足够了):
<script language="javascript" type="text/javascript">
function addMinutes(date, minutes) {
return new Date(date.getTime() + minutes * 60 * 1000);
}
function remainingMinutes(date) {
return Math.round((date - (new Date()).getTime()) / 60 / 1000);
}
var minutesForWarning = 5;
var sessionTimeout = parseInt("@Session.Timeout");
var showWarning = true;
var showRedirect = true;
var timeToWarn = addMinutes(new Date(), sessionTimeout - minutesForWarning);
var timeToEnd = addMinutes(new Date(), sessionTimeout);
function CheckTime() {
if (showWarning && new Date() > timeToWarn && new Date() < timeToEnd) {
showRedirect = false;
showWarning = false;
alert("Your session will expire in " + remainingMinutes(timeToEnd)) + " mins! Please refresh page to continue working.");
}
if (new Date() > timeToEnd) {
if (showRedirect)
alert("Session expired. You will be redirected to welcome page ");
document.getElementById('logoutForm').submit();
// window.location = "../Welcome.aspx"; // alternatively use window.location to change page
}
if (showRedirect == false)
showRedirect = true;
}
setInterval(CheckTime, 10000);
</script>
答案 4 :(得分:0)
您必须在此处使用客户端技术(javascript)。例如,您将使用javascript超时工具,然后显示警告。如果用户单击“确定”,则可能需要执行一些操作以使会话保持活动状态我会使用jquery.ajax方法sugest,并调用服务器,可以是一个虚拟调用 - 只是为了让会话保持活动状态。
答案 5 :(得分:0)
你可以使用jquery和setinterval函数在幕后进行Ajax发布以刷新超时(如果使用滑动过期),或者通过记录会话开始时间并从过期时间中减去来获取时间值的重新映射。 / p>
答案 6 :(得分:0)
你可以做的是使用一些javascript来触发消息。使用计时器在一段时间后(在您的应用程序中为会话超时设置的时间段 - 几分钟)后,在该时间段之后,向用户提供会话将超时的确认消息框。如果用户点击以保持sesion。在页面中进行虚拟回发,以便会话不会丢失。您也可以进行回叫,以便用户不会在页面中面对闪光灯。