HOWTO: Access Session outside of the page’s live cycle

You can­not access Ses­sion object or any other object which resides in page’s life cycle from out of the scope func­tions .This fol­low OOP rules but some­times com­pli­cate devel­op­ment process when you need to access ses­sion from exter­nal source. In this exam­ple i will exam­ine the way i use at any project to hack OOP for my needs. Maybe there is a bet­ter solu­tion but this is the best i’ve found so far.

real life example:

There was a web­site that used userID stored in the ses­sion in order to retrieve infor­ma­tion about logged user. All fine because most of the time access to ses­sion object comes from within page life cycle ( ie.Page_Load) itself but it has cer­tain com­pli­ca­tion when it comes to using func­tions whether these are on the same page but out­side of page life cycle scope or inside of App_Code directory.

Why would i access ses­sion out­side of the page’s life cycle ? Sim­ply because any­time web­site requests an  userID i need to check ses­sion for null in case user lost ses­sion or never logged in. Another rea­son could be archi­tec­tural change in the appli­ca­tion that won’t use userID stored in the ses­sion but in object of some kind. So much more ele­gant solu­tion will be to use exter­nal func­tion that does all the job for me. Gets an userID in case there is one and if not gets n0ne can be used in con­di­tional logic for exam­ple to redi­rect an user to login page.

So i’ve cre­ated a pri­vate func­tion to get an userID and if redi­rect­ToLo­gin vari­able is TRUE then it redi­rects. Sec­ond pri­vate func­tions retrieves the real userID by access­ing cur­rent con­text HttpContext.Current. Same way you can access any­thing from your page life cycle’s con­text ( ie.Request and Response) which i use in redi­rec­tion redi­rect­ToLogin­Page method. Most impor­tant is to under­stand that this kind of pro­gram­ming gives you flex­i­bil­ity in the future (ie. if you change your login page name or will start stor­ing whole user details in ses­sion as User object, this way you will just need to change one func­tion that will access User object stored in ses­sion rather search­ing and mod­i­fy­ing every place userID ses­sion vari­able was stored.)

code:


public static int getUserID(bool redirectToLogin)
{
int userID = getUserID();
if (redirectToLogin && userID == 0)
{
redirectToLoginPage();
}
return userID;
}

private static int getUserID()
{
int userID = 0;
if (HttpContext.Current.Session["userID"] != null)
{
userID = Convert.ToInt32(HttpContext.Current.Session["userID"]);
}
return userID;
}

private static void redirectToLoginPage()
{
HttpContext.Current.Response.Redirect("~/login.aspx");
}
Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DotNetKicks
  • DZone
  • LinkedIn
  • StumbleUpon
  • Technorati
  • Live
  • PDF

Tags: ASP.NET, session

Leave a comment