I need help with my MVC2 app session timeout warning. A popup should occur when the user is within "n" minutes of the session timeout. Is there some way to know that information or this has to be calculated. I have standard get/post actions but also AJAX requests. Thanks in advance.
1 Answer
An ASP.NET sessione expires n minutes after the last request to the server, so it's just a matter of knowing what n is, rendering it to the page, and using a simple Javascript timer to display a message when appropriate, like so:
<sctipt type="text/ecmascript">
var timeoutMins = <%= Session.Timeout %>; // HttpSessionstate.Timeout is the timeout period in minutes
setTimeout( informUser, 0.75 * ( timeoutMins * 60 * 1000 ) );
function informUser() {
alert("Your session is expiring shortly");
}
</script>
The 0.75 * ( timeoutMins * 60 * 1000) part converts the timeout length value to miliseconds and then scales it down to give the user time to react. You could extend the session automatically by making an AJAX request to the server (with the current ASP.NET session cookie, which is important).
Modifying this code to use a fixed alert period or calculating the "minutes left" figure is an exercise left to the reader.