MVC with JQuery: handling Session Expire

2019-01-11 14:17发布

问题:

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.

回答1:

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