Sessions never Die

session-expiration


A session is the time period for which a user interacts with a web application. Session objects can be used to store data which is specific to a particular user and these session objects can be accessed from anywhere within the application. A session is valid only for a particular length of time specified as its Timeout. On each request, if the sliding expiration is enabled (which is set by default in visual studio) the timeout period is reset to current time plus the timeout value. Default timeout period in ASP.Net is 20 minutes. We can manually alter the timeout period to the desired value by setting the timeout parameter in web.config. The maximum value possible is 24 hours.

Sometimes, the client may require increasing the timeout period or even avoiding the session from expiring while the user is logged in. This article briefly describes the various methods used to extend the expiration time of the session.

1.       Setting the timeout parameter in the web.config file

      The easiest method to set the timeout period is by setting it in the web.config file as shown below.


<sessionState cookieless="false" mode="InProc" timeout="90"> </sessionState>

 

The timeout=”90” implies that the session will be alive even if the user remains idle for 90 minutes.

But there is a problem associated with this. As you all know, the session objects are stored in the server memory. Setting the timeout value to anything greater than one hour will result in excessive memory being held on the server, as IIS holds the entire session memory for the duration of each session, in turn holding the sessions of thousands of users in heavily trafficked web sites, which in turn affects the performance of the application.

2.       By using Page Method

       The best method to refresh the session state is by making a request to the server. In this method we are making an Ajax request to the server at regular intervals of time, which in turn refreshes the session timeout, provided that the sliding expiration is enabled.

        We can use a JavaScript function to call the page method at fixed intervals of time. 

aspx:

  <script type="text/javascript">

  

   window.setInterval("RefreshSession()",300000);

   

   function RefreshSession()

   {

       PageMethods.RefreshSessionState();

   }

  </script>

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"> </asp:ScriptManager>

aspx.cs:

 

[WebMethod]

public static void RefreshSessionState()

{

   // do nothing

}

Here, we are calling the server method ‘RefreshSessionState’ at a fixed interval of time (5 minutes). So in every 5 minutes, the timeout period is being reset to current time plus the timeout value resulting in the session being alive forever.

This method is much effective if the need is to maintain the session particularly for one or two pages. If the requirement is to keep the session alive for the whole application, we need to add this code in each and every page of the application which is very time consuming. Instead, we can add the code in the masterpage. But including the scriptmanager in the masterpage will load the application which is not a good programming practice.

 

Meta refresh And Postback

This method also creates a request (postback) to the server in order to refresh the session state. This can be done using a meta-refresh tag placed inside an Iframe whose width and height is set to zero.

 In the master page, we have to include the Iframe as,

<iframe ID="SessionFrame" src="RefreshSession.aspx" frameBorder="0" width="0" height="0" runat="server"></iframe>

Now add a new page named RefreshSession.aspx and in the head section of the page, include the following code,

<meta id="MetaRefresh" http-equiv="refresh" content="7200;url= RefreshSession.aspx" runat="server" />

Here we have set the content value to 7200 seconds, which is equal to 2 hours. However, we will be setting this value ourselves in the Page_Load for this page, so this value can be ignored.

Add the following code to the Page_Load of RefreshSession.aspx.cs:

 

if (Session[“User”] != null)

{               

   // Refresh this page 60 seconds before session timeout,

   //effectively resetting the session timeout counter.

 MetaRefresh.Attributes["content"] =

Convert.ToString((Session.Timeout * 60) – 60) +

 

                    ";url=RefreshSession.aspx?q=" + DateTime.Now.Ticks;

}

Here we are adding a varying query string parameter at the end of the target URL (RefreshSession.aspx). Otherwise browsers will cache the RefreshSession.aspx page and the session never gets refreshed. So we are adding random query string values to avoid the browser caching of that page. The auto-refresh of the Iframe will occur 1 minute prior to the expiration of the session.

The next thing we need to take care of is to set the session timeout parameter in the web.config file to any value which is less than the IIS’s timeout value as discussed earlier. A value between 10 and 40 minutes will do the job perfectly.

The advantage of the above two methods over the conventional web.config session timeout method is that we can keep a session alive forever as long as the user’s browser window is open. Also as soon as the user closes the browser, the session will expire hence resulting in quickly freeing up the server memory which holds the session.

By .NET Team, Software Associates

Related Posts

    No related posts found
This entry was posted in .NET and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>