ASP.NET Session Object

ASP.NET provides a class called HttpSessionState, which is part of the namespace System.Web.SessionState.

Just like Request and Response objects, an HttpSessionState object is also created automatically for you in ASP.NET pages. This object is called “Session”. You can access various methods and properties of this object.
What is in a session ?

A session has several information including a session ID. Some information is created and used by the server itself. But the most important use of session is, it allows to store custom information.
You can store any key-value pairs in session.

How to store and retrieve values in ASP.NET session ?

Just like you can store values in variables, you can store values in session. Basically, you can assign values to session variables. See the following example:
The following code sample shows how to store a string value in session:
    Session(“UserId”) = “john”

In the above sample, the value “john” is assigned to a session variable called “UserId”. One important different here is, you do not declare the session variable as any datatype. Just assign any value to any session variable. The session variables will be automatically created when you simply assign values to them.
How long a session variable is valid ?

A session variable retains it’s value as long as the session is valid. Session variables are valid across all pages, as long as you access all those pages from the same browser and within the timeout period.

If you assign a value into a session variable from Page1.aspx and try to retrieve it from Page2.aspx, it will work. But if you try to access the Page2.aspx from another browser or close your original browser and open again, the session variable would have lost it’s value because a new session is created.

What can be stored in  a session? The above examples show storing and retrieving simple strings in session. But you can store complex datatypes like Dataset also into session. Many websites retrieve lot of user data from database and store into session so that it can be accessed faster from memory (session) rather than retrieving from database.

However, it is not reccommded to store lot of data into session for large websites. Session data is stored in memory and if there are thousands of online users at the same time, server may run out of memory.

Deixe um comentário

O seu endereço de email não será publicado. Campos obrigatórios marcados com *