Ok, I have this single-user web class that uses a session to maintain state. Initially, I thought that I would have to manipulate the session variables on each βsetβ so that the new values ββwere updated in the session. However, I tried to use it as is, and somehow it remembers the state.
For example, if you run this code on one page:
UserContext.Current.User.FirstName = "Micah";
And by running this code on another browser tab, FirstName is displayed correctly:
Response.Write(UserContext.Current.User.FirstName);
Can someone tell me (prove) how this data is saved in the session? Here is the class:
using System; using System.Collections.Generic; using System.Linq; using System.Web; public class UserContext { private UserContext() { } public static UserContext Current { get { if (System.Web.HttpContext.Current.Session["UserContext"] == null) { UserContext uc = new UserContext(); uc.User = new User(); System.Web.HttpContext.Current.Session["UserContext"] = uc; } return (UserContext)System.Web.HttpContext.Current.Session["UserContext"]; } } private string HospitalField; public string Hospital { get { return HospitalField; } set { HospitalField = value; ContractField = null; ModelType = null; } } private string ContractField; public string Contract { get { return ContractField; } set { ContractField = value; ModelType = string.Empty; } } private string ModelTypeField; public string ModelType { get { return ModelTypeField; } set { ModelTypeField = value; } } private User UserField; public User User { get { return UserField; } set { UserField = value; } } public void DoSomething() { } } public class User { public int UserId { get; set; } public string FirstName { get; set; } }
I added this to the clock and see that the session variable is definitely set somewhere:
(UserContext)System.Web.HttpContext.Current.Session["UserContext"];
As soon as the setter is called, the var session is immediately updated:
set { HospitalField = value;
source share