0

I'm having an issue retrieving a session variable on a page different than where it was set. The session variable holds a User Class Object that contains about 15 different user attributes for the current user.

I need this available on all of the pages and don't want to requery the database every time I land on a page. On my default.aspx I have the following code that runs on the page_init

protected void Page_Init(object sender, EventArgs e)
{
    // Get the logged in user id with acct domain (ie. acct05\abc123)
    masterNtId = Request.ServerVariables["LOGON_USER"].ToString();
    // Get the logged in user id (ie. abc123)
    masterNtID_short = masterNtId.Substring(masterNtId.IndexOf("\\") + 1);
    // Get the current page (ie. /PMM/page_name.aspx)

    UserObject user = TheUser.User.SearchUserWhitePages(masterNtID_short);
    Session["UserProfile"] = user;

    //Added to test that session is being set
    UserObject theuser = (UserObject)Session["UserProfile"];
    string name = theuser.get_UserName();

}

It successfully returns the session variable. However when I add the following code on another page that I navigate too from the default.aspx I get this error

"An exception of type 'System.NullReferenceException' occurred"

protected void Page_Load(object sender, EventArgs e)
{
    UserObject theuser = (UserObject)Session["UserProfile"];
    string name = theuser.get_UserName();
}

I set EnableSessionState = True on the aspx pages. I'm not sure what I am forgetting to do. Should I be setting my session state variable differently?

Tân
  • 1
  • 15
  • 56
  • 102
FlyFish
  • 491
  • 5
  • 22
  • 1
    Maybe the `Session` is timeout. – D-Shih Nov 19 '18 at 13:51
  • I doubt it, Unless it times out in 5 seconds. – FlyFish Nov 19 '18 at 14:03
  • 1
    My hunch is that this could be a serialization error. Basically: can it be converted to-and-from a `string` easily? Does your `UserObject` marked as `[Serializable]`? Does it have a default constructor (e.g.: `UserObject()`?) Check out https://stackoverflow.com/questions/10230880/serializing-session-state-in-asp-net for a little more information about this. – Chris Nov 19 '18 at 14:16
  • I tried adding serialization to no effect. Yes, it has a default constructior. I've even gone so far as just trying to just store a single value in the session and then trying to retrieve it. Session["UserName"] = user.get_UserName(); then this string name = (String)Session["UserName"]; This works on the page where it is being stored, but I still get a null on any other pages when I try to retrieve it. – FlyFish Nov 19 '18 at 16:16

0 Answers0