C# ASP.NET中的会话超时警告
我有一个asp.net站点,我需要在会话达到超时(比如10分钟)时弹出/层/警报。弹出窗口将显示您的帐户会话将由于不活动而退出,并有一个“继续会话”按钮或一个“注销”按钮 我在网上看到了不同的方法,但最好/正确的处理方法是什么?如果弹出窗口打开时间过长,是否需要额外超时?C# ASP.NET中的会话超时警告,c#,asp.net,.net,session,iis,C#,Asp.net,.net,Session,Iis,我有一个asp.net站点,我需要在会话达到超时(比如10分钟)时弹出/层/警报。弹出窗口将显示您的帐户会话将由于不活动而退出,并有一个“继续会话”按钮或一个“注销”按钮 我在网上看到了不同的方法,但最好/正确的处理方法是什么?如果弹出窗口打开时间过长,是否需要额外超时? <script type="text/javascript"> var sessionTimeoutWarning = "<%= System.Configuration
<script type="text/javascript">
var sessionTimeoutWarning = "<%= System.Configuration.ConfigurationManager.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>
var sessionTimeoutWarning=“”;
var sessionTimeout=“”;
var sTimeout=parseInt(sessionTimeoutWarning)*60*1000;
setTimeout('SessionWarning()',sTimeout);
函数SessionWarning(){
var message=“您的会话将在另一个会话中过期”+
(parseInt(sessionTimeout)-parseInt(sessionTimeoutWarning))+
“分钟!请在会话到期前保存数据”;
警报(信息);
}
这一点以前已经解决过,例如。
然而,目前还没有一种完全可靠的方法可以做到这一点,因为:
- 如果用户使用同一会话打开了多个窗口,则一个窗口可能比另一个窗口最近,并且最旧窗口上的客户端会话超时将过时/不正确
- 如果您往返到服务器以查看当前会话到期时间是什么,您将对其进行扩展,从而破坏弹出/警报的目的
在此期间之后,向用户显示会话将超时的确认对话框。如果用户单击以保留sesion。在页面中进行虚拟回发,以便会话不会丢失。您还可以进行AJAX调用,以便用户不会看到页面重新加载并丢失输入数据。下面是一些带有jQuery的JavaScript,用于警告用户ASP.NET表单身份验证超时,并在达到超时时将其重定向到登录页面。它还可以改进并适应会话超时。每当用户通过单击、键入或调整大小与页面交互时,它还会通过“ping”服务器来重置身份验证超时 请注意,这确实会通过每次单击、按键、调整大小来为服务器添加负载,但这是非常小的。尽管如此,如果有许多用户不断地输入,您仍需要评估其影响。我想不出另一种方法来实现这一点,因为服务器必须参与进来,因为这就是超时过期的地方 还要注意的是,在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);
在服务器上,您需要返回剩余时间的操作。您还可以添加更多信息
public JsonResult Ping()
{
return Json(new {
timeout = FormsAuthentication.Timeout.TotalMilliseconds
},
JsonRequestBehavior.AllowGet);
}
我去看了of的文章,我喜欢这篇文章的总体思路,但是代码可能需要一些简化。这是我的版本。有关平板电脑/移动设备问题,请参见以下内容:
<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>
var minutesForWarning=4;
var sessionTimeout=parseInt(@Session.Timeout”);//razor语法,否则使用
var showWarning=true;
函数SessionWarning(){
showWarning=false;
警报(“您的会话将在“+分钟ForWarning+”分钟后过期!请刷新页面以继续工作。”);
//如果同时过期,请留出一秒钟时间调用重定向fct
setTimeout(函数(){showWarning=true;},1000);
}
函数重定向towelcomepage(){
如果(显示警告)
警报(“会话已过期。您将被重定向到欢迎页面。”);
document.getElementById('logoutForm').submit();
//window.location=“../Welcome.aspx”//或者使用window.location更改页面
}
setTimeout('SessionWarning()',(sessionTimeout-minutesForWarning)*60*1000;
setTimeout('RedirectToWalComePage()',sessionTimeout*60*1000);
在平板电脑或手机上,你不能指望setTimeout,因为当设备被锁定或浏览器处于非活动状态时,javascript执行会暂停。相反,我在做定期检查(就我而言,我认为每10秒就足够了):
功能添加分钟数(日期,分钟){
返回新日期(Date.getTime()+分钟*60*1000);
}
功能剩余分钟数(日期){
返回Math.round((date-(new date()).getTime())/60/1000);
}
var minutesForWarning=5;
var sessionTimeout=parseInt(@Session.Timeout”);
var showWarning=true;
var=true;
var timeToWarn=addMinutes(new Date(),sessionTimeout-minutesForWarning);
var timeToEnd=addMinutes(new Date(),sessionTimeout);
函数CheckTime(){
如果(显示警告和新日期()>timeToWarn和新日期()timeToEnd){
如果(显示重定向)
警报(“会话已过期。您将被重定向到欢迎页面”);
document.getElementById('logoutForm').submit();
//window.location=“../Welcome.aspx”/
<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>
<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>