Latish Sehgal's Blog

Asp.Net Session Timeout Control

As web application developers, we depend on the Session to store data pertaining to the user. It’s a common scenario that the user might take a half an hour break to take a phone call or a meal while using the application and come back to find out the site behaving in an unexpected manner because his session would have expired (default value for session timeout is 20 minutes). As a developer, it’s a good practice to check a session variable for null value before using it, but you can create a much more user friendly environment by redirecting the user to a web page indicating that his session has timed out. The best way to do this is by creating a user control that you can just drop on your master or content page as desired.

I looked around for such solutions, and I have described below 2 such good implementations that should cover most scenarios.

Implementation 1
You can create a web control similar to what Peter Bromberg has outlined here.

This control checks for the HttpSessionState’s IsNewSession property and the presence of the ASP.NET_SessionId cookie to determine if the user session has expired. It redirects the user to a timeout page if the session has expired. All you need to do is drop the control on your page and assign the RedirectURL property to your timeout page. The control works for both synchronous and aynchronous postbacks (for those of you using Asp.Net Ajax), and the only downfall for this method is that there’s no way to warn the user that his page is about to timeout.

Implementation 2
If you would like to warn the user before his session actually times out, you can create an AJAX friendly control similar to what Travis Collin’s solution.

This control pops up a warning to the user some time before his session times out and gives him a chance to save his session. You can configure the UI of the warning and the time for warning and timeout while using the control. The only thing to watch out for here is that the developer has to make sure the session (and form) timeout value are in sync with the one configured on the control. I faced a small issue in this implementation because it was not recognizing asynchronous postbacks as user activity. To fix this, all i had to do was add a client side handler for page load and reset the timeout there as well.

    initialize : function()



        Sys.Application.add_load(Function.createDelegate(this, this._handlePageLoaded));



        _handlePageLoaded: function(sender, e)