Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC with JQuery: handling Session Expire

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:

  • When the client reaches the session timeout, each of my controllers inherits a class that checks if the session is alive (looking up on some stuff like the site session, database session, etc) and redirects the client to a new page saying that the session expires; but the case is different when I'm using JQuery ajax to call methods of the controllers on some button clicks, cause it skips the validation of the inherited class and allows me to stay on the page, but when the controller tries to end the execution of method, obviously it throws .Net errors: objects are not created as instance of objects, Session variables not found, etc.. all because of the expired session that was not handled because of the asynchronic method call.

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.

like image 229
lidermin Avatar asked Feb 23 '10 14:02

lidermin


People also ask

How check session expired in MVC?

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.

How is session timeout implemented in MVC?

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.


1 Answers

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';
    }
}
like image 149
BalusC Avatar answered Oct 07 '22 20:10

BalusC