Tutorials » AspNet tutorials »

Purpose of Session variables

This article explains the purpose of Session variables

In most of the web sites, when a user log In in the login page, they set few variables to session.

if (bLoginSuccess = true) then
Session("UserId") = txtLoginName.Text
Session("Name") = GetUserNameFromDatabase(txtLoginName.Text)
Response.Redirect ("LoginError.aspx")
end if

The above code stores the user's userid into a session variable called "UserId". All other pages will check if the user id is set in the session and if not, it will give an error message saying "you have not logged in".

dim userId as string = Session("UserId")
if ( userId = "" ) then
Response.Write ("Welcome " & Session("Name"))
end if

The above validation will be required only in the pages which needs user login. For example, in AspSpider.com, you can access most of the pages without logging in. Only when you submit an article or feedback, we will use the above code and validate your login. If you are not logged in, we will redirect you to login page automatically.

If you look at the top left corner of this site, you can either see 'Login" or "Welcome <Name>". We have used a logic similar to what is shown below, to display appropriate message.

dim userId as string = Session("UserId")
if ( userId = "" ) then
Response.Write("<a href='Login.aspx'>Login</a>")
Response.Write ("Welcome <a href='MyAccount.aspx'>" & Session("Name") & "<a>)
end if

As you can see from the above examples, session variables are used to store small key-value pairs in the memory. You can use session variables to store values from one page and access the values from other pages for the same user. If you set a value in session variable from one page, you can retrieve the value from any other page in the same session.

The most important point to remember is, whatever value you store in session will be valid only until the session expires. Also, this value will not be accessible for another user/session.

Next Chapter: How does server identify a session?
Previous Chapter: The ASP.NET Session Object
More Chapters: ASP.NET Tutorials
More Tutorials: Tutorial Index

Top Contributors
    Last 7 Daysmore...

    Awards & Gifts

    Online Members

    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India