title: Where's the best place to store a custom "User" object for the duration of an ASP.NET session?
body: <p>I have an ASP.NET application that needs to remember some info about a user (and what company they are from) across pages, within a session.</p>
  
  <p>I imagine this is a requirement of just about any ASP.NET application of a certain size. I've used a few different approaches over the years.</p>
  
  <p>In the past, I've passed around an id in querystring parameters like so:</p>
  
  <pre><code>site.com/page.aspx?usrid=1&amp;companyid=2
  </code></pre>
  
  <p>and then instantiated the object on each page (from the database).</p>
  
  <p>Another common way of doing it is storing my objects in session variables:</p>
  
  <pre><code>Session["User"] = currentUser;              // store at login
  User currentUser = (User)Session["User"];   // retrieve on some other page
  </code></pre>
  
  <p>which saves a trip to the DB, but I worry about memory used if the User object is complex and the site has many concurrent users.</p>
  
  <p>I have recently inherited an application that uses public properties on the master page, like this:</p>
  
  <pre><code>Master.theUser = currentUser;         // store at login
  User currentUser = Master.theUser;    // retrieve on some other page
  </code></pre>
  
  <p>This saves the cast, and looks more readable to me I think, but I don't know if it's better or worse performance-wise. It also has some logic in the getter where if the private value is null, it tries to get it from the Session variable, though I'm not sure if that's never used (or used <em>every</em> get!?) or what.</p>
  
  <p>My latest idea is to use my page class. I have a custom page class derived from the standard System.Web.UI.Page base class. It includes objects like CurrentUser as public properties. This seems to work OK. I like it even better.</p>
  
  <p>But I really don't know what's going on under the covers. Can anyone give an opinion on which approach is better and why? </p>
  
  <p>Alternative suggestions for doing this are also welcome.</p>
  
  <p><strong>Update:</strong>
  I've done some checking use trace.axd and Trace.Write and it looks like neither the masterpage version nor the custom page class version "remember" the values between pages. The "get" methods have a line of code that checks if the User property is null, and if so, reads it from the session variable. This happens when a page accesses the property (Master.User or the derived class's this.User) for the first time on a given page, then subsequent requests can get the value (without going to the session variable).</p>