views:

56

answers:

2

Hi

Is there a way of detecting when an AJAX request (using jQuery) to an ASP.NET MVC application redirects me to the login page?

I'm getting partial views rendered using an ajax call, but when the user has been signed out (for whatever reason), instead of returning a 302 or some other indication (that I can see) I get the login form returned to me...

Thanks,

Kieron

+1  A: 

The xmlhttp object will auto follow a 302 response automatically, you can check this using firebug/fiddler, your first response will be a 302 redirect and the xmlhttp will immediately request the location contained in the 302 response resulting in your login page being responded.

There are a few ways you can avoid the above scenario.

1) Add a meta refresh tag that takes the user to a signout action method and redirects them to the login page a few seconds before the session is due to time out (best option for security imo)

2) A minute or so before timeout show the user a dialog which tells them they are about to be signed out. If they click "stay signed in" within the minute make a quick ajax call which will keep the session valid for the next x minutes, if the user does not respond simply issue a client redirect to your signout action.

3) the ugly solution could be to check the ajax response to see if it is the login page (test for a certain id or similar), if so do a full page client redirect to your signout action....not nice but will work

redsquare
I suppose a custom xmlhttp object could be used too, which jQuery does support - see xhr - http://api.jquery.com/jQuery.ajax/
Kieron
@Kieron, not sure how that helps you out here really.
redsquare
I'd hope you can inspect the the result, before it does a redirect...
Kieron
Nope you cannot, I remember going through this trauma!!
redsquare
Bugger, ok - thanks redsquare.
Kieron
+1  A: 

You could create a new attribute similar to the solution given to this question by @Craig Stuntz. When making your Ajax request, you could pass in the following function where you can display some kind of custom dialog if the user's session has timed out:

    function OnAjaxError(context) {
        if (context._response.get_statusCode() == '403') {
            // Show a dialog telling the user they have been logged out
        }
        else {
            // Show a dialog telling the user there has been an error
        }
    }
s1mm0t