lidermin
lidermin

Reputation: 2832

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:

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.

Upvotes: 11

Views: 10987

Answers (1)

BalusC
BalusC

Reputation: 1109132

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';
    }
}

Upvotes: 16

Related Questions