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.
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.
- <sessionState mode="SQLServer" cookieless="true" regenerateExpiredSessionId="true" timeout="30" sqlConnectionString="Data Source=MySqlServer;Integrated Security=SSPI;" stateNetworkTimeout="30"/>
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 -
- protected void btnSubmit_Click(object sender, EventArgs e)
- {
- Session["FirstName"] = txtfName.Text;
- Response.Redirect("Default2.aspx");
- }
Second Page -
-
- if (Session["FirstName"]!= null)
- {
- lblString.Text = Session["FirstName"];
- }
Thanks for reading the article. Hope you enjoyed it.