Tutorial :How to detect a redirect to login when using AJAX with ASP.NET MVC 2



Question:

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


Solution:1

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


Solution:2

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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »