Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>(Updated for completeness)<br> You can access session variables from any page or control using <code>Session["loginId"]</code> and from any class (e.g. from inside a class library), using <code>System.Web.HttpContext.Current.Session["loginId"].</code></p> <p>But please read on for my original answer...</p> <hr> <p>I always use a wrapper class around the ASP.NET session to simplify access to session variables:</p> <pre><code>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; } } </code></pre> <p>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, e.g like this:</p> <pre><code>int loginId = MySession.Current.LoginId; string property1 = MySession.Current.Property1; MySession.Current.Property1 = newValue; DateTime myDate = MySession.Current.MyDate; MySession.Current.MyDate = DateTime.Now; </code></pre> <p>This approach has several advantages:</p> <ul> <li>it saves you from a lot of type-casting</li> <li>you don't have to use hard-coded session keys throughout your application (e.g. Session["loginId"]</li> <li>you can document your session items by adding XML doc comments on the properties of MySession</li> <li>you can initialize your session variables with default values (e.g. assuring they are not null)</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload