Sunday, November 1, 2009

Prevent IIS Session Timeout in ASP .NET

There are scenarios that a user may want to keep a long session alive. For example, a help desk operator logs into a web application and takes phone calls and in between submits changes to the backend systems. The phone call may last over an hour and the operator may stay in one web page and need that session to be valid when she submits the changes.
In ASP.NET, there are several common simple solutions for that. One of them is to set the session timeout attribute (minutes) in web.config.
<sessionState mode ="InProc" timeout="xxx"/>
Some people are confused at the timeout setting in web.config and another in IIS and ask which overwrites which. A simple experiment shows that the setting in web.config always overwrites the setting in IIS.
However, this is not complete for ASP .NET 2.0+. Open IIS->Application Pools->Select the Application pool for your application->Properties->Performance, set the idle timeout for "Shutdown worker processes after being idle for xxx minutes".
Otherwise, the worker process is still stopped after 20 minutes(default) and your session state will be lost.
Another way, if we do not want to rely on the settings in IIS, is to keep the session alive by ourselves in the application. Some people use an invisible frame and set auto refresh in http header, but if you are using a master page, that behavior will be propagated to all ASP pages. With .NET 2.0+ and a little bit Ajax, we have a simpler solution - add a timer in UpdatePanel. The timer will trigger a partial postback periodically, thus prods the session to be alive.
<asp:Content ID="ct" ContentPlaceHolderID="cphMain" runat="Server">
  <asp:ScriptManager ID="scriptMgr" runat="server" />

  <%-- Your content here --%>

  <%-- Heartbeat every 15min to keep session alive --%>
  <asp:UpdatePanel ID="updatePanel" runat="server">
      <asp:Timer ID="timerPing" runat="server" Interval="900000">
1. Managing Session TimeOut using Web.Config
2. Preventing Session Timeouts in C# ASP .NET


dotnetchris said...

Very elegant solution.

--Al- said...

I have seen (and used) enough examples of little javascripts to do this to last me a lifetime. Let me add to dotnetchris and say *very* elegant solution which not only is simpler, but easier to read/understand than the others. Had to actually try it to believe it worked. My only regret is not having found this post years ago.


Anonymous said...

The downside is the amount of network traffic. An UpdatePanel sends as much data to the server as posting the whole page.
Update panels are great, but if you only want a heartbeat sent, use Ajax.