Wednesday, 25 December 2013

The Session Object

Hypertext Transfer Protocol (HTTP) is a stateless protocol. In stateless transactions the Web Server does not keep track of these transactions. Every transaction is considered as an independent transaction.

Sessions were designed to overcome this limitation. Sessions are used to store  the information of the user logged in to the Website. The information that is stored is used to identify the user sending a request to the Web Server. For each new user, the Server object checks the user Session ID. The user is considered as 'active' and is permitted to continue with the application if the user has a valid Session ID. If the Server object unable to find Session ID, the Server object creates a Session Object for the user.

Session object is used to store information about a user. When a user logs in to the Website, the Web Server creates a Session ID for that user. The Web server sends the Session ID to the user's computer. This Session ID is stored in the user's computer as Cookies. The information is retained when the user browses from one page to another within the same application.

Advantages of Session Object:
  • The information is retained for the duration of the user session and cannot be shared or accessed by other users of the application.
  • The server destroys the Session object after the session expires or is terminated.
Example:

This example demonstrates how Session variable is used from one page to another.

WriteSessionVariable.aspx.cs

protected void Submit_Click(object sender, EventArgs e)
{
Session["FirstName"] = FName.Text;
Session["LastName"] = LName.Text;
Response.Redirect("ReadSessionVariable.aspx");
}

FName and LName is a TextBox ID.
FirstName and LastName is a Session Variable Name.

Output:
ReadSessionVariable.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
First_Name.Text = "First Name: " + Session["FirstName"];
Last_Name.Text = "Last Name: " + Session["LastName"];
}

First_Name and Last_Name is a Label ID.

Output:

No comments:

Post a Comment