HttpContext.Current.Session null item

2019-01-28 11:37发布

问题:

i'm storing in HttpContext.Current.Session current user, SiteUser is single-tone class that presents current active siteuser, and when he logged i'm creating new SiteUser() in controller and in constructor adding him to the session:

public static SiteUser Create()
{
    HttpContext.Current.Session[sessionKey] = new SiteUser();

    return HttpContext.Current.Session[sessionKey] as SiteUser;
}

then, with every request to the server services i'm check is user available in session:

public static SiteUser Current
{
    get
    {
        if (HttpContext.Current.Session == null || HttpContext.Current.Session[sessionKey] == null)
        {
            throw new SiteUserAutorizationExeption();
        }

        return HttpContext.Current.Session[sessionKey] as SiteUser;
    }
}

otherwise i'm generate non-auth-user exception and redirect him to the logon page. but sometimes HttpContext.Current.Session[sessionKey] is null, but HttpContext.Current.Session doesn't null and FormsAuthenticationTicket is available and Expired property is also false. can somebody help me, why HttpContext.Current.Session[sessionKey] can be null?

UPD: webconfig session settings: <sessionState mode="InProc" timeout="20" />

UPD: sessionKey is: public const string sessionKey = "SiteUser";

UPD2: i'm forget to add, that in session also stored Culture settings:

HttpContext.Current.Session["Culture"]

and when exception hits, that HttpContext.Current.Session[sessionKey] is null, culture-item isn't

UPD3: i have downloaded symbol tables of source .NET Framework and set breakpoints at SessionStateItemCollection on changing collection items. and i resolved some mistakes: 1) all collection items are null — "culture" is setting up after 2) it happens at the session end event i can't understand how it can be, because at web.config session timeout is set 20

回答1:

sessionKey may be changing, you probably only need to do:

HttpContext.Current.Session["CurrentUser"]

Or the session may be expiring, check the timeout:

http://msdn.microsoft.com/en-us/library/h6bb9cz9(VS.71).aspx

Or you may be setting the session value from somewhere else, normally i control access to Session/Context object through one property

static readonly string SESSION_CurrentUser = "CurrentUser";

public static SiteUser Create() {     
 SiteUser.Current = new SiteUser();      
 return SiteUser.Current;
}

public static SiteUser Current {     
 get {         
  if (HttpContext.Current.Session == null || HttpContext.Current.Session[SESSION_CurrentUser] == null) {             
   throw new SiteUserAutorizationExeption();         
  }          
  return HttpContext.Current.Session[SESSION_CurrentUser] as SiteUser;     
 } 
 set {
  if (!HttpContext.Current.Session == null) {
   HttpContext.Current.Session[SESSION_CurrentUser] = value;
  }
 }
}