What is Session State and How do You Use Session State?

Part of the You Can Learn ASP.Net and C# series.
By Ken Brown
Editor, YouCanLearnSeries.com
Updated:
January 30, 2005

Session state is a server side tool for managing state. Every time your web app goes to the server to get the next request, the server has to know how much of the last web page needs to be "remembered" when the new information is sent to the web page. The process of knowing the values of controls and variables is known as state management.

When a page postback occurs, ASP.Net has many techniques to remember state information. Some of these state management information methods are on the client side and others are on the server side. Client side methods for maintaining state include query strings, cookies, hidden fields and view state.

Most client side state management modes can be read by users and other programs, meaning that user ids and passwords can be stolen. But session state sits on the server and the ability for other users to capture this information is reduced and in some cases eliminated.

Session State is Server Side

Session state is server side. In session state, a special session id is stored on the server. This session id identifies a specific ASP.Net application. The session id is assigned to the calling browser.

The importance of this method is the server, especially in a web farm, can know if a particular user is a new user or has already visited this web page. Imagine in a web farm, where you have multiple servers serving the same web page. How do the servers recognize unique visitors? It is through the session id. Even if server one gets the initial request, server two and server three can recognize user A as already having a session in process.

Now the server can store session specific information about the current user. Is there highly critical sensitive information about the user that needs to be remembered? Like credit card information or name, address and phone number? This information can be kept out of the prying eyes of internet identity thieves with session state.

How to Set Session State

To set session state, it is as easy as setting a key value pair:

Session["Name"] = txtName.Text; or Session.Add("Name",txtName.Text);
Then to retrieve session state after the postback

txtName.Text = Session["Name"].ToString();
You can store simple objects like strings into the session state and you can also store more complex objects like arrays and structs and any object derived from System.Object.

Here is a list of supported methods of the HttpSessionState class.
Abandon Cancels the current session
Add Adds a new item to session state
Clear Clears all values from session state
CopyTo Copies the collection of session state values to a one dimensional array, starting at the specified index in the array.
Equals Determines if the specified object is equal to the current session state object
GetEnumerator Gets an enumerator of all session state values in the current session
GetType Gets the System.Type of the current instance
Remove Deletes an item from the session-state collection
RemoveAll Clears all session state values
RemoveAt Deletes an item at a specified index from the session state collection
ToString Returns a System.String that represents the current System.Object


As you can see by looking at the supported methods, you can add, remove, remove all, convert to a string and detrmine type.

There are 3 ways to store session state.

  1. In Process
  2. Session State Service
  3. Storing it in MSSQL server
The default location is in the ASP.Net process. This is known as in-process. Whenever you stop the Web Server or restart IIS you will lose all of your session state information.

State Service runs in a different process than ASP.Net, so you don't have to worry about losing information when ASP.net goes down. State Service also enables you to share your state across multiple servers (web farm) and multiple processors on one server (web garden).

A disadvantage to using session state is because it is stored on the server you must go to the server to get the information which is slower than if it was stored on the client side.

For the greatest safety and security of your session state use MSSQL server to store session state. Then even if the SQL server dies, you still maintain the info needed for session state. A great methodology to use if you are running an eCommerce shopping cart. Users dislike it when their session dies and they don't know if they have pruchased something or not.

Since it is stored outside of the web server and the client, then you don't lose information if the web garden or web farm go down either. To use session state on the SQL server alter your web.config file:

<sessionState mode="SqlServer" sqlConnectionString="data source=NameOfSQLServer;
user id=Kenno;password=mypassword" />
This allows you to connect to the database server and store the required information for session state into the SQL server.

So to store required information outside of the client and to persist the information pass each page load use Session State. It is part of the HttpSessionState class and comes from the Page class. It is easy to use, but does require resources on the server, which could slow response time. You can store sessionState in-process, state server or in SQL server. You don't need to store everything in sessionState, but you add a level of trust to the items stored in sessionState.


Home| About Us | NewsLetters | Contact Us |

Copyright © 2004-2014 You Can Learn Series

You Can Learn Series Home Page You Can Learn Series
You Can Learn Series Home Page Home            About the creators of YouCanLearnSeriesAbout Us      Contact YouCanLearnSeriesContact Us      Site map of YouCanLearnSeriesSite Map      Privacy Policy of You Can Learn SeriesPrivacy Policy       Terms of Use of You Can Learn Series web siteTerms of Use       YouCanLearnSeries RSS feed for C# tips and tutorials     
C# and ASP.Net Programming TipsC# and ASP.Net      SQL Tutorial, tips and tricks for DBA'sSQL       Landscaping Tips for Home GardenersLandscaping       WeightLifting Tips for the Young and OldWeightLifting       Kennos BlogBlog       Good health TipsGoodHealth       Learn about Great Travel DestinationsTravel     Web Business TipsWeb Business            You Can Learn Series' Online StoreStore



You Can Learn C# and ASP.Net SeriesC# and ASP.Net
  Using Client Side Code with C# and ASP.NetClient Side Code
  Using Client Side State Management with C# and ASP.NetClient Side State Management
  Create a C# Class in Visual StudioCreate A Class
  Use A Class in C#Use A Class
  Create a Solution in Visual StudioCreate a Solution
  Create a Project in Visual StudioCreate a Project
  Create an RSS feed for your Web SiteCreate an RSS Feed
  Create an RSS feed for your Web SiteListItemCollection
  Set Events in ASP.NetSet Events ASP.Net
  Set Events in C#Set Events C#
  What is Session State and How to Use it.Session State
  Creating and Using the C# SortedList ObjectSortedList Object
  Stylesheet Tips for Visual Studio .Net and ASP.NetStyleSheet Tricks
  Using C# MethodsUsing Methods
  Pass Objects to MethodsPass Objects to Methods
  Pass Objects from MethodsPass Objects from Methods
  Using Client side State management like ViewState and Hidden fieldsView State
  LDAP, What is Lightweight Directory Access ProtocolWhat is LDAP
  Build an LDAP ReaderBuild an LDAP Reader
  Convert information from LDAP to a Web ServiceLDAP To Web Service
  Question of the dayQuestion of the Day

You Can Learn SQL SeriesSQL
You Can Learn Landscaping and Gardening SeriesLandscape Tips
You Can Learn WeightLifting SeriesWeightLift Tips
Kenno's BlogBlog
You Can Learn Good Health SeriesGood Health Tips
You Can Learn Good Series NewslettersNewsletters
Learn about Great Travel DestinationsTravel
You Can Learn Series Web Business TipsWeb Business Tips
Merchandise Available from You Can Learn SeriesMerchandise

Sara A Mason - Sci-Fi Author of Renegades




Americas Public Schools