You cannot access Session object or any other object which resides in page’s life cycle from out of the scope functions .This follow OOP rules but sometimes complicate development process when you need to access session from external source. In this example i will examine the way i use at any project to hack OOP for my needs. Maybe there is a better solution but this is the best i’ve found so far.
real life example:
There was a website that used userID stored in the session in order to retrieve information about logged user. All fine because most of the time access to session object comes from within page life cycle ( ie.Page_Load) itself but it has certain complication when it comes to using functions whether these are on the same page but outside of page life cycle scope or inside of App_Code directory.
Why would i access session outside of the page’s life cycle ? Simply because anytime website requests an userID i need to check session for null in case user lost session or never logged in. Another reason could be architectural change in the application that won’t use userID stored in the session but in object of some kind. So much more elegant solution will be to use external function that does all the job for me. Gets an userID in case there is one and if not gets n0ne can be used in conditional logic for example to redirect an user to login page.
So i’ve created a private function to get an userID and if redirectToLogin variable is TRUE then it redirects. Second private functions retrieves the real userID by accessing current context HttpContext.Current. Same way you can access anything from your page life cycle’s context ( ie.Request and Response) which i use in redirection redirectToLoginPage method. Most important is to understand that this kind of programming gives you flexibility in the future (ie. if you change your login page name or will start storing whole user details in session as User object, this way you will just need to change one function that will access User object stored in session rather searching and modifying every place userID session variable 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");
}