Technology Inside Out!

Index ¦ Archives ¦ Atom ¦ RSS

Maintaining Sessions in Asp.net

aspnet_sessions

Session is amongst the most important part in creating asp.net applications. It is a variable where you can put data between page requests when the pages are either posting or redirecting to each other. It can contain small amount of data containing string, complex arrays or numbers.

In Asp.net the copy of session variable is stored for each individual session and session are managed with cookies. Cookies are data created on server and are sent back to browser in response to http request. In asp.net session cookies are created automatically once the page is loaded into the browser.

During the page load, the server detect a new user and then creates a session cookie for the new user and then sends back to the browser and then use cookies for each subsequent request. Session variable can be of many types from string to complex numbers and arrays.The session variable are stored in SessionStateItemCollection Class.

****The format to create a session object in asp.net is

Session[key_name] = (any dynamic or arbitrary name)

Let us consider an example where we are using a login interface with 2 aspx pages (Session_page.aspx,Landing_Page.aspx) and username and password are being stored in session and displaying the username and password on Landing_Page.aspx.

Asp.net tutorial : Maintaining sessions in asp.net

Let us use "Test_User" as username and "Test_Password" as password. (Note that at this point of tutorial the values are not comparing with the database values we are just assuming that "Test_User" and "Test_Password" are registered and we have reached Landing_page.aspx )

Asp.net tutorial : Maintaining sessions in asp.net (Image 2)

The main coding is done on the "Login" button where we will fetch the values from text boxes and store the values in sessions.
The C# code for the login button is given as follows

    protected void Login_Button(object sender, EventArgs e)
    {
        Session["User_name"] = TextBox1.Text;
        Session["Password"] = TextBox2.Text;
        Response.Redirect("~/Landing_Page.aspx");
    }

where TextBox1.Text contains the text entered in the username field and TextBox2.Text contains the text entered in password field, once the login button is pressed the session is created and the username and password is stored in the session variable, now we can use this session variable anywhere within our project.

After clicking the login button here is the Landing_page.aspx where the session variable is used, here is the output of Landing_Page.aspx

Asp.net tutorial : Maintaining sessions in asp.net (Image 3)

Here is the code for the Landing_Page.aspx

protected void Page_Load(object sender, EventArgs e)
    {
            Session_Username.Text = Session["User_Name"].ToString();
            Session_Passowrd.Text = Session["Password"].ToString();
    }

Now since Label7.Text expects a string but there is now way in asp.net that it automatically identifies it as a string so we have to explicitly store the value as a string, now there are 2 ways, the first way is using C# , the code is

 Label7.Text = (String)Session["User_Name"];

and the second way is to append .ToString() function to the session variable, the code is given below

 Session_Username.Text = Session["User_Name"].ToString();

Some FAQ's related to Sessions using asp.net

Q: What happens if we close the browser and reopen Landing_Page.aspx, will the session be maintained ?
A: The answer is NO once the browser is closed the cookies are destroyed and so as the session.

Q: So what happens if we directly open the Landing_Page.aspx page ?
A: Since we directly opened the Landing_Page.aspx page, no session was created for username and password so it will display blank values for username and password. But its not recommended to either redirect or display an error message. For example consider the following code segment

protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["User_Name"] == null || Session["Password"] == null)
        {   //Your redirection code here.
            Top_Header_Text.Visible = false;
            Session_Username.Text = " No session created, you will be soon redirected to Session_Page.aspx. ";
            Session_Password.Visible = false;
            Username.Visible = false;
            Password.Visible = false;
        }
        else
        {
           Session_Username.Text = (String)Session["User_Name"];
            Session_Password.Text = Session["Password"].ToString();
        }
    }

Then the output will be

Asp.net tutorial : Maintaining sessions in asp.net (Image 4)


© The Geeky Way. Built using Pelican. Theme by Giulio Fidente on github.

Disclaimer Privacy policy