Reputation: 1989
Hi I am trying to develop a functionality that will track everytime there is a new session created in a web app aka a user logs in.
I have created a class called "StateBag.cs"
using System;
using System.Text;
[Serializable()]
public class StateBag
{
#region Business Methods
// To catch the event of a New Session //
private bool _NewSession = false;
public bool NewSession
{
get { return _NewSession; }
set { _NewSession = value; }
}
#endregion
}
On the login page, just before login:-
// Declaration Region. //
private StateBag _Bag;
if (Session.IsNewSession)
{
_Bag = new StateBag();
_Bag.NewSession = true;
// ViewState["StateBag"] = _Bag;
Session["NewSession"] = _Bag;
}
On the Main page, after a successful login:-
// Declaration region. //
StateBag _Bag
{
get
{
return (StateBag)Session["NewSession"];
}
}
if (_Bag.NewSession == true)
{
// Do my stuff........ //
_Bag.NewSession = false; // set new Session back to false//
}
I m having problems retrieving _Bag... it comes back as Null...
hence an error message :- "Object reference not set to an instance of an object."
Can anyone help me retrieve the NewSession property which I set to "True" on the login page?
Upvotes: 0
Views: 331
Reputation: 218950
You're storing it in ViewState
:
ViewState["StateBag"] = _Bag;
And retrieving it from Session
:
return (StateBag)Session["NewSession"];
ViewState
and Session
are two completely different things, they don't share the same objects. You need to pick one place to persist the data and always retrieve it from that same place.
Note: ViewState
renders data to the client, so I wouldn't suggest using that to store anything that you don't want a client to be able to see/modify.
Upvotes: 3