Sessions are used to store information in order to use it during later page requests or in other web pages in a web application. By default Cookies are used to identify which session belongs to which browser. There is an option that you can set in your web.config file to use Cookieless Sessions; however you should keep in mind that for most web applications the Session ID should be kept private and when using Cookieless Sessions the Session ID is displayed in the query string.
In .NET there are three session states: InProc, StateServer, and SQLServer.
By default web applications are set up to use InProc.
Where are Sessions stored?
InProc
The session is kept as live objects on web server (aspnet_wp.exe). It is stored in memory and is the fastest out of the three options; however, you should keep in mind that the more data you store in session, the more memory on the web server is consumed. This could affect the performance of your applications running on the web server. Also keep in mind that you cannot use InProc sessions in a web garden for many reasons I'm not going to get into.
StateServer
The session is serialized and stored in memory in a separate process (aspnet_state.exe). State Server can run on another machine, whereas InProc is specific to the machine the website is running on. You should keep in mind that the cost of serialization/deserialization of the session can affect performance if you're storing lots of objects.
SQLServer
The session is serialized and stored in a table in an SQL server. It requires you have a database available and you should think about how you are going to secure the connection to the database. This is the slowest of the three options but is required in order to store persistent data.
How do I use Sessions in my web application
It's really quite simple.
In the following example I use VB.NET to store the text value (userName) of a text box in session during a button click:
Expand|Select|Wrap|Line Numbers
- Private Sub btn_button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_button1.Click
- Session("userName") = txt_userName.Text
- End Sub
Expand|Select|Wrap|Line Numbers
- Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
- Dim userName as String = Session("userName")
- lbl_welcome.Text= "Welcome to working with Sessions " + userName + "!"
- End Sub