Session In ASP.NET

What is 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 using the session we can store the value and access it in another page or throughout the application.

Why Session

As you know that HTTP is a stateless protocol, it means every request is an independent request. Browser does not know about previous request and data. So, every previous request data 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.

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

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

  1. <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 object of class, list, datatable, etc. It is secure.

Disadvantages of Session

It makes your website slow, if you use it. It is because the session value stores on server memory. So, every time it need 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 in one page and access it on another.

First Page
  1. // Set Session values during button click  
  2. protected void btnSubmit_Click(object sender, EventArgs e)  
  3. {  
  4.    Session["FirstName"] = txtfName.Text;  
  5.    Response.Redirect("Default2.aspx");   
  6. }  
Second Page
  1. // Get Session values   
  2.   
  3. if (Session["FirstName"]!= null)  
  4. {  
  5.    lblString.Text = Session["FirstName"];  
  6. }  
Thanks for reading the article. Hope you enjoyed it.

 

Up Next
    Ebook Download
    View all
    Learn
    View all