Sunday, February 6, 2011

Session Variables

Requests between servers and browsers are handled via HTTP - Hypertext Transfer Protocol.

HTTP is a stateless protocol. This means that each request is serviced as it comes; after the request is processed, all of the data is discarded. No state is maintained across requests even from the same client. In a nutshell, data from one page is generally unavailable on the next page etc.

When we create a Desktop Application, often we use variables to hold data that persists for the life of the program execution. There are several ways to achieve the same result on the ASP.NET platform. One way is to use Session Variables.

A Session Variable can be read from anywhere in your website. You can use them to store information for the lifetime of a single users visit. Session variables do not need to be declared, they can be written on the fly.

Session("SessionName") = value

That's not to say that we have stopped using variables, not at all. But in the ASP.NET environment we can no longer rely on them to store application wide data.

Checking the Session Exists

Sessions Time-out if the user is idle for a period of time. This period of time is variable from server to server but generally it is a matter of only a few minutes. Because of this, we should always check if the session exists before we attempt to reference one.

If Session.Item("CustomerID") IsNot Nothing Then
            Response.Write(Session("CustomerID"))
Else
            Response.Write("Session CustomerID does not exist")
End If

No comments:

Post a Comment