Introduction
When you visit a website in your browser you are sending a request. It is a HTTP request. HTTP stands for Hypertext Transfer Protocol and it is an application layer protocol designed within the framework of the Internet Protocol Suite. A web server treats each HTTP request for a page as an independent request because HTTP is a stateless protocol. Suppose you are visiting two pages (About Us and Contact us) of a website. First you request the "About Us" page and get that information; that is the first HTTP Request. Then you navigate to the "Contact Us" page; that creates another HTTP request so you make two requests from the same client (web browser) for the web server but both are independent and the web server does not know who is visiting. So the problem is, how can the server determine that these two requests are from the same client and suppose you store values on one page then how to retrieve that in another page? The solution to these problems is ASP.NET sessions. The ASP.NET Session State stores and retrieves values for a user. An ASP.NET Session State identifies requests from the same browser during a limited time window as a session, and provides a way to persist variable values for the duration of that session.
HTTP Session
An HTTP session is a sequence of network request-response transactions. An HTTP client initiates a request by establishing a Transmission Control Protocol (TCP) connection to a specific port on a server (typically port 80). An HTTP server listening on that port waits for a client's request message. Upon receiving the request, the server sends back a status line, such as "HTTP/1.1 200 OK", and a message of its own. The body of this message is typically the requested resource, although an error message or other information may also be returned.
Suppose you have two clients (Client1 and Client2). Client1 makes two requests and Client2 makes one request. Depending on the number of users, the web server creates various sessions. Client1 and Client2 use different sessions. Client1 makes two requests. The first HTTP request is sent to the web server and the web server uses the HTTP Request Header to determine whtether the SessionId already exists. If it does not exist then the web server creates a SessionId that is unique for the user and sends in a HTTP response header but it makes a second request that creates a SessionId to be used in the HTTP Request Header and will not create another sessionId for that user. In other words, SessionId will be the same in the next request of Client1 so the web server can know that both requests are from the same client (web browser). Let's see that in Figure 1.1.
![ASP.NET-Session-in-Client-Server-architecture]()
Figure 1.1 ASP.NET Session in Client Server architecture
Session Identifier
Sessions are identified by a unique identifier. It is 120 bit identifier in ASP.NET. It can be read using the SessionID property. The client requests a web page in the application from the web server, then the server checks the SessionID value sent from the web browser. If the SessionID value is not supplied then ASP.NET starts a new session and the SessionID value for that session is sent to the browser with the response. By default, SessionID values are stored in a cookie. However, you can also configure the application to store the SessionID value in the URL for a "cookieless" session.
Example
We are developing a web application that has three pages. Check Table 1.1 for the list of application pages.
![table- ASP.NET-Session]()
Table 1.1 List of application pages
![Workflow-of-application-request]()
Figure 1.2 Workflow of application request
Now run the application and go to each page one by one.
Step 1: Run the application from your Visual Studio (HTTP 200).
When you run the application you make an HTTP request for the Contact.aspx page and it is the first HTTP request to the web server from the web browser so the HTTP Request Header doesn't have a SessionID.
Step 2: Redirect to another page (HTTP 302).
Now fill in the contact form and click on the button that redirects to another page using Response.Redirect(). We are sending the request to the same page so the HTTP Request Header doesn't conatin an ASP.NET_SessionId but as a response you will get a ContactDetail.aspx page. So the web server checks the request header for a SessionID. We know here that the HTTP Request Header doesn't have an ASP.NET_SessionID so the web server creatrs it and stores it in the state provider. That SessionID is set in the Response Header along with a reponse from a web server.
![ASP.NET_SessionId-set-in-Response-Header]()
Figure 1.3 ASP.NET_SessionId set in Response Header
Now you can see that an ASP.NET_SessionId has been created by the server and set in the Response Header.
Step 3: Request for Contact Details (HTTP 200)
Now an ASP.NET_SessionId has been created by the web server so in the next requests, the Request Header has that ASP.NET_SessionId and it is the same as the Response Header. This ASP.NET_SessionId will be used to identify the specific user session and ensures that this request is from the same client that created the previous request.
![ASP.NET_SessionId- in-Request-Header]()
Figure 1.4 ASP.NET_SessionId in Request Header
Now you can see that your Request Header's ASP.NET_SessionId is the same as the previous Response Header's ASP.NET_SessionId. Here the SessionId is supplying the Request Header so the web server does not create a new SessionId and intead gets the session data of the user that already has the session with this same id. You get the same sessionId in subsequest requests from the same browser.
Storing and retrieving values from Session
Storing and retrieving values in a session are quite similar to that in dictionaries. The main application programming interface for working with Session State is the HttpSessionState class. This object is exposed by the Page.Session, Context.Session, UserControl.Session, WebService.Session, and Application.Session properties. This means that you can access Session State from just about anywhere.
The collection of session variables is indexed by the name of the variable or by an integer index. You do not need to declare a session variable or explicitly add it to the collection. The following example shows how to create session variables in an ASP.NET page for the Name and Email of a user, and set them to values retrieved from TextBox controls on a Button Click event. The following code sinnept from an application stores a value in a session and redirects to another page on button clicks.
- protected void btnSubmit_Click(object sender, EventArgs e)
- {
- Session["Name"] = txtName.Text;
- Session["Email"] = txtEmail.Text;
- Response.Redirect("http://localhost/SessionExample/ContactDetail.aspx");
- }
- protected void Page_Load(object sender, EventArgs e)
- {
- if (Session["Name"] != null && Session["Email"] != null)
- {
- string name = Session["Name"].ToString();
- string email = Session["Email"].ToString();
- Response.Write(string.Format("My name is :{0} and Email is :{1}",name,email));
- }
- }
Advantages of Sessions
Here is a list of advantages of sessions.
- It helps maintain the user data and user settings separately.
- We can store any type (value type and reference type) data in a session.
- It is easy to store and retrieving values.
- It is not stored client-side so it is secure.
- Session State works with browsers that do not support HTTP cookies.
- Session management events can be raised and used by your application.
Disadvantages of Session
Here is a list of disadvantages of session.
- It is stored on the server so it takes more memory.
- It stores each user data separately on the server so it can decrease the performance of data.
- The StateServer and SQLServer mode of a session needs serialized and de-serialized sessions so overhead is involved.
Conclusion
In conclusion I want to share some basic points you should remember. These are:
- When you use Session State, a session cookie named ASP.NET_SessionId is added to your browser automatically.
- By default, the ASP.NET Session timeout is 20 minutes.
- It is a server-side state management technique because each session is stored on the server.