ASP.NET session variables, cookies, query string parameters, etc.
Part three of a five-part series of blogs

There is a range of techniques for remembering information in ASP.NET across pages and even sessions, including session variables, cookies, query string parameters and crosspage postback. This blog explains how to use each of these techniques, together with the pros and cons of each.

  1. Remembering State between Pages
  2. Passing Data by Query String in the URL
  3. Passing Data using Session Variables (this blog)
  4. Using Cookies to Remember Things
  5. Cross-Page Postback

This page is part of an online tutorial in ASP.NET.  Wise Owl's main business is running classroom-based training courses - have a look at our other .NET courses.

Posted by Andy Brown on 16 October 2012

You need a minimum screen resolution of about 700 pixels width to see our blogs. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.

Passing Data using Session Variables

Session variables are nuggets of information which your ASP.NET page stores on the server computer. As soon as a user finishes their session on your web site, the nuggets are deleted.

Creating Session Variables

Creating a session variable couldn't be simpler!  In C#:

// store the text entered as session variables

if (txtContains.Text.Length > 0) {

Session["Contains"] = txtContains.Text;


if (txtStatus.Text.Length > 0) {

Session["Status"] = txtStatus.Text;


In VB:

'store the text entered as session variables

If txtContains.Text.Length > 0 Then _

Session("Contains") = txtContains.Text

If txtStatus.Text.Length > 0 Then _

Session("Status") = txtStatus.Text

Reading Session Variables Back

As so many things in .NET, session variables are returned as objects, so you have to convert them into the right sort of data before use.  Here's how we could pick up on the search criteria entered, in C#:

string Contains;

string Status;


// retrieve session variables, if set

try {

Contains = Convert.ToString(Session["Contains"]);

Status = Convert.ToString(Session["Status"]);

} catch {

Contains = "Not passed";

Status = "Not passed";


litContains.Text = Contains;

litStatus.Text = Status;

Or again in VB:

'retrieve session variables, if set

Dim Contains As String

Dim Status As String


Contains = Convert.ToString(Session("Contains"))

Status = Convert.ToString(Session("Status"))

Catch ex As Exception

Contains = "Not passed"

Status = "Not passed"

End Try


litContains.Text = Contains

litStatus.Text = Status

Disadvantages of Session Variables

The above code shows that session variables are easy to set and retrieve, but they do have disadvantages:

Disadvantage Notes
Easy to make errors Misspelling a session variable won't generate an error - but nor will it give the right results.
Memory-consuming Your web server will have to hold session variables for every website user, so the amount of memory used can be large (although you can get round this by time-limiting session variables, as below).

In practice you wouldn't use session variables to transfer fields between two pages, as this would be an ASP.NET sledgehammer to crack a nut.

How to Use Session Variables to Authenticate Users

Wise Owl always use session variables is to hold an authenticated user's id.

Suppose that Jo Bloggs has signed on to a website with the correct user name and password.  To code this, go to the code-behind for the website's master page (you do have one, don't you?) and add this code in VB:

Partial Class blog

Inherits System.Web.UI.MasterPage




#Region "Authenticating user"


'property to return user id

Property UserId As Integer



Return Convert.ToInt16(Session("UserId"))

Catch ex As Exception

Return 0

End Try

End Get

Set(value As Integer)

Session("UserId") = value

End Set

End Property


'on page load, check user exists

Private Sub Page_Load(sender As Object,

e As System.EventArgs) Handles Me.Load


'if the user not authenticated, make them log on

If UserId = 0 Then Response.Redirect("frmLogon.aspx")


End Sub

#End Region

End Class

For C#, the code would look like this:

public partial class blog : System.Web.UI.MasterPage


#region Authenticating user

protected void Page_Load(object sender, EventArgs e)


// if the user not authenticated, make them log on

if (UserId == 0) { Response.Redirect("frmLogon.aspx"); }



// property to return user id

int UserId {

get {

try {


} catch {




set {

Session["UserId"] = value;





Whenever a user loads a page based on the master page, the page load event will check to see if the user id is set, and if not, redirect the user to a log on page.

One thing to be careful of with this approach - you must make sure that your log on page frmLogon.aspx isn't based on the same master page, otherwise you'll end up going round in circles!

This blog has 0 threads Add post