views:

115

answers:

1

You are using ASP.NET MVC with jQuery. You make a lot of AJAX calls. You want to notify the user if they click something and the session has timed out. Does anyone have a good existing solution to this that also includes notifying the user of timeout after initiating an AJAX request?

(There are known solutions for non-AJAX ASP.NET apps that involve detecting the timeout in Global.asax and redirecting to a specific page. Redirecting the AJAX request, however, is problematic because the user either won't see it, or will see it in the wrong context.)

This is something almost every application needs so I just want to make sure I don't reinvent the wheel. Thanks!

+1  A: 

Here's what I do: when my server detects a session timeout, it responds with the reauthentication page, and it also sets a special header in the response. For Ajax, I just have my handler look for that header, and if it sees it it forces the surrounding page (i.e., location.href or whatever) to reload (with an extra "nonce" parameter to make sure it bypasses the browser cache).

Note that my solution isn't specifically an ASP.NET thing.

Pointy
That's OK, ASP.NET not required... I am more curious about client-side handling. So, if it's a normal request/response, they get the timeout notice / login page, and if it's an AJAX request/response, you check for this header and redirect to that page? That sounds like a decent way to handle it.
Pete
It works OK for me so far :-) Note that what happens when the outer page reloads is that the server detects the timeout *again*. Therefore it redirects to the re-auth page, and it saves the original URL as a form parameter there so that after authentication it can get the user back to the page they were on originally. Setting and detecting the header is, as you might imagine, extremely simple - it doesn't even have to have any particular value.
Pointy
Thanks Pointy. I got this solution working tonight. This makes a much better user experience and I don't need to handle page requests and ajax requests any differently on the server side.
Pete