mattgcon
mattgcon

Reputation: 4858

Global Variable for ASP.Net MasterPage

I am converting a webapp from a frameset layout to Masterpage layout. Each of the pages within the frameset use a common custom class to aquire the logged in user, this custom class inherits from Page.

I thought that an interface would be the proper way to convert this however I was really wrong. What is the best and most efficient means to store a global variable or class so that each content page for the Masterpage can reference the logged in user class?

Upvotes: 2

Views: 1868

Answers (1)

Antonio Bakula
Antonio Bakula

Reputation: 20693

Make it a simple static class with static method that will return logged user class, there is no need to tie this code with ASP.NET page. If getting the logged on user requires some time vise expensive operations (like DB query for example) store logged user class instance in the session. Something like this :

public static class Users
{

  public static User GetLoggedUser()
  {
    if (HttpContext.Current.Session["LoggedUser"] != null)
    {
      return (User)HttpContext.Current.Session["LoggedUser"];
    }
    else
    {
      User usr = GetLoggedUserSomehow(); // here goes your current code to get user
      HttpContext.Current.Session["LoggedUser"] = usr;
      return usr;
    }
  }

}

Upvotes: 1

Related Questions