In order to add objects from the Session use the following
This adds an object to the Session state, the name and the
value of the item to be added being passed to this method as parameters. Further,
the HttpSessionState class is present in the System.Web namespace in the
Alternatively, we can add objects to the Session.
HttpSessionState.Session[“UserName”] = “Joydip”;
This automatically creates a new item called “UserName” in
the Session State Collection (if none exists) and sets its value to “Joydip.”
The following method is used to retrieve a previously stored
object from the Session state.
string userName = HttpSessionState.Session["UserName"].ToString();
Note that the ToString() method is called because data is
stored in the Session state as objects. Therefore, the conversion or casting to
the appropriate type is necessary in the above example to retrieve the current
User’s name as a string.
The following method is used to remove an object from the
This method deletes the object specified as parameter from
the Session State Collection, provided the same exists. In this case, if the
session-state collection does not contain the element specified, the collection
remains unchanged, but no exception is thrown.
To clear the Session use either of the following:
The difference between the Session.Abandon() and the
Session.Clear() method is that if you call Session.Abandon(), Session_End will
be fired (for InProc mode) and in the next request, Session_Start will be
fired. Session.Clear( ) just clears the session data without killing it.