I have a .NET MVC application which makes extensive use of AJAX and modal windows. I have an action filter that handles the expiration of a user’s session which redirects to the login page. However, if the request is made from the modal window, the action result that is returned is the login page which then loads in the modal window.
I have been trying to find a way to either redirect the main page to the login when the session expires but I have had no such luck as the Session_End event is fired form the server and I have no access to the Response object. I was wondering if anyone else has encountered a problem like this, and if so, how did you overcome it?
I think I finally figure out a solution for this. While its not as elegant as I had hoped, it works (which is more than I have found so far). The solution lies around the OnBegin AjaxOption and some Jquery. My ActionLink (it could also be an Ajax.BeginForm that this is applied to) looks like this
I have a controller action in my Account controller that checks session, in my case I am storing the user object so i check to see if it is null, and returns ‘True’ or ‘False’ as content. The OutputCache is important otherwise your results will be cached.
The last part is the check_session function specified as the OnBegin handler. The Jquery ajax call hits the session check action and checks the response. If the response is ‘True’ (meaning the session has expired), it sets the location of the page back to the home page (or google in this case).
There are several things to remember if using this method. The first is that this will run asynchronously. If you have data sensitive code that you are calling you will still need to perform a server side check on session. This code is intended to simply redirect to the login page (or home page) if the session is expired during an ajax call. The second thing is that the check_session function will need to be wired into the OnBegin event of all of your Ajax calls. If anyone has any tips or suggestions for improving this method, I would love to hear them. I hope this helps somebody.