How to declare and use a session variable (C#) RRS feed

  • Question

  • User-866590679 posted
    Ok, this should be real simple. I want to declare 2 string variables in the Session_Start of the global.asax. Then read and use them throughout the app. What's the proper syntax? All the examples I've found just start using them without showing declarations.
    Wednesday, December 10, 2003 2:36 PM

All replies

  • User-732283392 posted
    In your Global.asax file: VB.NET Sub Session_Start(ByVal sender As Object, ) Session.Add("varName", varValue) End Sub C# void Session_Start(Object sender , EventArgs e) { Session.Add("varName", varValue) } Where varName is the name of the variable that you will use to access the value, and varValue being the value of the variable.
    Thursday, December 11, 2003 2:47 PM
  • User-866590679 posted
    What about typing? I guess since no type is given, that's why it needs to be cast when it's used? -cp-
    Friday, December 12, 2003 1:40 PM
  • User2084210377 posted

    An example for declaring the type for a session var

    I declare and add data to this

    List<ListItem> imageFiles = new List<ListItem>(); 

    Session Var Below

    List<ListItem> imageFiles = Session["imageFiles"] as List<ListItem>


    Session["imageFiles"] = imageFiles as List<ListItem>;


    String ImageName = (String)Session["ImageName"];
    ImageName = "1001.bmp";

    Friday, December 11, 2015 2:40 PM
  • User753101303 posted


    Or you could consider to use something such as http://www.codeproject.com/Articles/16656/Manage-ASP-NET-Session-Variables-using-the-Facade

    In short the idea is to expose strongly typed properties using session variables for storage Under the Hood. You can then get IntelliSense, strongly typing, find references etc... on your sesssion variables...

    Friday, December 11, 2015 2:46 PM
  • User765422875 posted

    I'd create a session wrapper vs. just setting session variables all over the place. A wrapper class will give you type safety and a central place to make all changes. Additionally, you can swap out Session for a data-store of your choice at any point without a major refactoring effort.

    public static class ExampleSessionHelper
        public static string SomeVariable
            get { return HttpContext.Current.Session["SomeVariable"] as string; }
            set { HttpContext.Current.Session["SomeVariable"] = value; }
        public static int SomeVariable2
            get { return (int)(HttpContext.Current.Session["SomeVariable2"]); }
            set { HttpContext.Current.Session["SomeVariable2"] = value; }
        // etc...

    Friday, December 11, 2015 2:47 PM