1 February 2014

Storing and retrieving Sessions

Storing and retrieving values in session are quite similar to that in View State. We can interact with session state with the System.Web.SessionState.HttpSessionState class, because this provides the built-in session object in ASP.NET pages.

The following code is used for storing a value to session:

//Storing UserName in Session
Session["UserName"] = txtUser.Text;

Now, let's see how we can retrieve values from session:

//Check weather session variable null or not
if (Session["UserName"] != null)
{
    //Retrieving UserName from Session
    lblWelcome.Text = "Welcome : " + Session["UserName"];
}
else
{
 //Do Something else
}

We can also store other objects in session. The following example shows how to store a Dataset in session.

//Storing dataset on Session
Session["DataSet"] = _objDataSet;
The following code shows how we to retrieve that Dataset from session: 

//Check weather session variable null or not
if (Session["DataSet"] != null)
{
    //Retrieving UserName from Session
    DataSet _MyDs = (DataSet)Session["DataSet"];
}
else
{
    //Do Something else
} 
Session ID

ASP.NET uses 120 bit identifier to track each session. This is secure enough and can't be reverse engineered. When a client communicates with a server, only the session ID is transmitted between them. When the client requests for data, ASP.NET looks for the session ID and retrieves the corresponding data. This is done in the following steps:
·         Client hits the web site and information is stored in the session.
·         Server creates a unique session ID for that client and stores it in the Session State Provider.
        ·         The client requests for some information with the unique session ID from the server.
·         Server looks in the Session Providers and retrieves the serialized data from the state server and type casts the object.

No comments:

Post a Comment