Session In ASP.NET

What is a Session?

Session is a state management technique that is used to manage the state of a page or control throughout the application. So, I mean to say that by using the session we can store the value and access it on another page or throughout the application.

Why Session?

As you know HTTP is a stateless protocol, which means every request is an independent request. The browser does not know about previous requests and data. So, every previous request data is lost and you cannot retrieve previous data. Basically using the session, we store the data in session and access it anywhere as per requirement. It provides application-level state management.

HTTP

There are a lot of other techniques that are used for state management such as ViewState, Cookie, etc.

There is a default time to expire the session, you can increase and decrease it using the configuration.

<sessionState 
    mode="SQLServer" 
    cookieless="true" 
    regenerateExpiredSessionId="true" 
    timeout="30" 
    sqlConnectionString="Data Source=MySqlServer;Integrated Security=SSPI;" 
    stateNetworkTimeout="30" />

Session

Advantages of Session

Sessions are used to maintain the state of user data throughout the application. It stores any type of object. Using the session, you can add variable values as well as any type of object such as an object of class, list, data table, etc. It is secure.

Disadvantages of Session

It makes your website slow if you use it. It is because the session value is stored on server memory. So, every time it needs to serialize the data before storing it and deserialize the data before to show the user.

Example

The following is an example that shows you how can you store the session value on one page and access it on another.

First Page

// Set Session values during button click
protected void btnSubmit_Click(object sender, EventArgs e)
{
    Session["FirstName"] = txtfName.Text;
    Response.Redirect("Default2.aspx");
}

Second Page

// Get Session values

if (Session["FirstName"] != null) 
{ 
    lblString.Text = Session["FirstName"]; 
}

Thanks for reading the article. Hope you enjoyed it.


Similar Articles