How do I warn the user that their web session is about to time out?

给你一囗甜甜゛ 提交于 2019-11-29 10:56:39

问题


I've checked around for a solution but I don't seem to get any directed to asp.net mvc. Basically I'm looking for a solution where a user is notified a minute before the session expires.

The ideal solution will be count down notification that will have an option to renew the session.

If the countdown timer expires without the user refreshing the page, I need to log them out.


回答1:


Something like this:

public class YourController : Controller {
    public ActionResult TheAction() {
        ViewData["SessionTimeout"] = Request.Session.Timout;
        ViewData["SessionWillExpireOn"] = DateTime.Now.AddMinutes(Request.Session.Timeout);
        return View(info);
    }
}

and this:

<span>Your session will expire: <%= ViewData["SessionWillExpireOn"].ToString() %></span>
<span id="countDown" style="display:none></span>
<script type="text/javascript">
    var sessionTimout = <%= ViewData["SessionTimeout"].ToString(); %>;      
    var approximateStart = new Date();
    var notifyAfter = new Date(approximateStart + (sessionTimout - 1)*60*1000);
    function startCountDown() {
        setTimout(function() {
            var now = new Date();
            document.getElementById('countDown').style.display = 'inline';
            document.getElementById('countDown').innerHTML = "Countdown: " + now.getMinutes();
            if (now >= notifyAfter)
                alert('About to expire...');
        }, 5000);
    }
    document.onload=startCountDown;
</script>

Wrote the View in notepad, so please check the syntax. I also don't remember exactly the DateTime stuff in JS.

Anyway you should see the idea.



来源:https://stackoverflow.com/questions/1740230/how-do-i-warn-the-user-that-their-web-session-is-about-to-time-out

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!