How could I handle the session expire on a MVC application that has JQuery Ajax method calls on certain pages. The issue is the following:
How could I handle this behaviour, and which is the best way to handle it (trying as much as possible to not modify so much parts of the code of the application)?
Thanks in advance.
PD: It might be useful to tell that I'm using $.post()
from Jquery.
In web applications, session holds the information of current logged-in users. So, if the session expires in 20 minutes, then it is redirected to login page. In that case, we need to check if session exists (not null) in every action/ every controller which requires authentication. We have to two methods to check.
config file in the MVC application. If you want to increase the session timeout then open your application web. config file which is placed under your application root folder. By default, the ASP.NET MVC session timeout value is 20 minutes.
This is typically an unrecoverable error which is usually best to be displayed as a standalone error page. Configure the webapplication to display a customized 4nn/5nn
error page and setup jQuery as follows:
$(document).ready(function() {
$.ajaxSetup({
error: handleXhrError
});
});
function handleXhrError(xhr) {
document.open();
document.write(xhr.responseText);
document.close();
}
This way the server-side 4nn/5nn
error page will be displayed as if it's been caused by a synchronous request. I've posted a simliar topic about the subject before.
Another way is to postpone the session timeout ajaxically. Use setInterval()
to fire a poll request to the server (which in turn basically grabs the session from the request) every time-of-session-expiration-minus-ten-seconds or so.
setInterval(function() { $.get('poll'); }, intervalInMillis);
But the caveat is that the session will survive as long as the client has its browser window open, which may at times take too long. You can if necessary combine this with sort of activity checker so that the chance that the session get expired will be minimized. You still need to combine this with a decent 4nn/5nn
error handler.
$(document).ready(function() {
$.active = false;
$('body').bind('click keypress', function() { $.active = true; });
checkActivity(1800000, 60000, 0); // timeout = 30 minutes, interval = 1 minute.
});
function checkActivity(timeout, interval, elapsed) {
if ($.active) {
elapsed = 0;
$.active = false;
$.get('poll'); // Let server code basically do a "get session from request".
}
if (elapsed < timeout) {
elapsed += interval;
setTimeout(function() {
checkActivity(timeout, interval, elapsed);
}, interval);
} else {
alert($.messages.timeout); // "You will be logged out" blah blah.
window.location = 'http://example.com/logout';
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With