Purpose of Session variables

logo asp.net

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)
else
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.Redirect("Login.aspx")
else
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 m
ost 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 “. 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("Login")
else
Response.Write ("Welcome " & Session("Name") & ")
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.


Deixe um comentário

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