Friday, March 4, 2011

Maintain HTTP sessions of a web application in a centralized place

We create so many HTTP sessions and forget to kill them. Or, we create Http session object in different pages for the same functionality. They may or may not be having the same name. This creates so much of confusions and also leads to bugs (abnormal behavior) of the application if they are not properly  controlled or utilized.

The solution is to define any http session at one place (in the class) and use them in the most appropriate and wise manner.

In the APPCode, add a class with name SessionMgr.

public class SessionMgr
{
      public static string UserID
      {
          get
              {
                 return (string) HttpContext.Current.Session["UserId"];
               }
         set
              {
                HttpContext.Current.Session["UserId"]=value;
               }
       }
}

Like this as many session variables used in the project can be defined in one class and wherever, you need them call them by classname.variable name (SessionMgr.UserID).

In this way, you will always have control over the sessions in your project.

No comments:

Post a Comment