Saturday, October 18, 2008

Maintain Session Variables in ASP .Net Projects

Most of the ASP .net web projects maintain their session variables in an inconsistent way. Sometimes it’s harder to read and maintain. Here is a best way to maintain session variables in your web project. This will increase the maintainability and readability. 

Approach: Add a new class to the web project and expose session objects as static properties.

1: using System;
2: using System.Web;
3:  
4: namespace SessionTest
5: {
6:     /// 
7:     /// Hold all session variables
8:     /// 
9:     public static class ApplicationSession
10:     {
11:         /// 
12:         /// Hold the search key
13:         /// 
14:         public static string SearchKey
15:         {
16:             get
17:             {
18:                 return Convert.ToString(HttpContext.Current.Session["SearchKey"]);
19:             }
20:             set
21:             {
22:                 HttpContext.Current.Session["SearchKey"] = value;
23:             }
24:         }
25:     }
26: }
 
Web Page
 
1: using System;
2: using System.Web.UI;
3:  
4: namespace SessionTest
5: {
6:     /// 
7:     /// Code behind for the page
8:     /// 
9:     public partial class SessionTest : Page
10:     {
11:         protected void Page_Load(object sender, EventArgs e)
12:         {
13:             if (!IsPostBack)
14:             {
15:                 // Access the session
16:                 string currentSearchKey = ApplicationSession.SearchKey;
17:  
18:                 // Set new value
19:                 ApplicationSession.SearchKey = "Customer";
20:             }
21:         }
22:     }
23: }