Skip to content

Instantly share code, notes, and snippets.

@smetronic
Created November 15, 2016 12:25
Show Gist options
  • Save smetronic/d6b720dfe45c2a59ae050042fa0ff6e2 to your computer and use it in GitHub Desktop.
Save smetronic/d6b720dfe45c2a59ae050042fa0ff6e2 to your computer and use it in GitHub Desktop.
Access session variables from any page
public class MySession
{
// private constructor
private MySession()
{
Property1 = "default value";
}
// Gets the current session.
public static MySession Current
{
get
{
MySession session =
(MySession)HttpContext.Current.Session["__MySession__"];
if (session == null)
{
session = new MySession();
HttpContext.Current.Session["__MySession__"] = session;
}
return session;
}
}
// **** add your session properties here, e.g like this:
public string Property1 { get; set; }
public DateTime MyDate { get; set; }
public int LoginId { get; set; }
}
//This class stores one instance of itself in the ASP.NET session and allows you to access your session properties in a type-safe way from any class
int loginId = MySession.Current.LoginId;
string property1 = MySession.Current.Property1;
MySession.Current.Property1 = newValue;
DateTime myDate = MySession.Current.MyDate;
MySession.Current.MyDate = DateTime.Now;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment