Products
Database Search Solution (New Version) Search Control SEO Pager Highlighter Shortcut Controls Crypt Package Free ASP.NET Controls
Geotargeting Component ASP.NET Media Player Control Flash Video Player Control Services
ASP.NET Telecommute Jobs Free IP Location Lookup Test .Net Regular Expressions CSS/Table/DIV Page Layouts Custom Programming Article Sites Master List |
How To Write, Read and Delete Session State VariablesHTTP is stateless protocol which doesn't provide information if two requests come from the same visitor or from two different visitors. Data like IP address, browser type, operating system etc., are not reliable for visitor identification. ASP.NET session state is one method to solve this problem. Session state can be used to identify same visitor between requests. Session variables act as global variables, visible from all .aspx pages on website. Each visitor has its own session collection which is created on first request and destroyed when session expires. By default, session expires after 20 minutes of inactivity. How to write and read session state variablesTo create, read or delete session state variables, we'll use Session property (full path is System.Web.HttpContext.Session). Session property is type of System.Web.SessionState.HttpSessionState. Writing and reading of variables is simple. An example could look like this: [ C# ] // Create new session variable named "MySession" and add some data [ VB.NET ] ' Create new session variable named "MySession" and add some data How to avoid possible errors when reading sessionType of all session values is System.Object, so you can store any .Net type in session state. But, when read value, you need to convert it back from Object to original type. This could lead to error if session is expired. When session is expired, variable is deleted and session object will return null value. Attempt to convert null to original type could cause a null reference error, cast error, lead to unexpected behavior in web application etc. To avoid this, it is better to check first is session variable equal to null, and if it is null, use some default value. So, more robust code for reading session variable could look like this: [ C# ] // Default value, used if session is null [ VB.NET ] ' Default value, used if session is null Session state variables act as global variables for individual visitor. They are visible from all .aspx pages. But, they are not visible for other server side technologies, like classic ASP, PHP, JSP etc. Each visitor has unique string named Session id which is used for identification, and its own session variables in form of collection of key-value pairs. Except null value issue, one more problem when working with ASP.NET sessions could be hard coding of session variables names. Variables are hard coded in example above where name of variable "UserTheme" is written two times as plain string. Problem is even bigger if you use some variable on many pages and on every place write literals. If we want to change that variable name, from "UserTheme" to something different, it will require change in all places where this variable occurs. Also, while coding, there is always a possibility to misspell variable name. In that case ASP.NET will not return an error or warning. It will simply assume that this is a second variable with slightly different name. So, for names of session variables, better avoid hard coded strings. You can store names in some public class but that solves only part of the maintenance problems. Manipulate session by using wrapper classAs better solution that solves all these problems, you can create a wrapper class. Wrapper class will have static properties which will represent session variables. On this way, complete session code is on single place which is easy to maintain. On pages, use wrapper class property to read or write session variable: A SessionWrapper class, with one example property that represents session variable "UserTheme", could look like this: [ C# ] using System; [ VB.NET ] Public Class SessionWrapper You can add as many properties as you have session variables, and add new item when needed. Save this class to website's App_Code folder. To call example session variable "UserTheme" on any .aspx page, simply use SessioinWrapper.UserTheme, like bolded part in next example: [ C# ] protected void Page_Load(object sender, EventArgs e) [ VB.NET ] Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) SessionWrapper class logic is very simple, but powerful. It solves all common problems when coding sessions: How to delete session variables or complete sessionIf visitor is not made any request in time interval longer than specified with sessionTimeout parameter (20 minutes by default), that session will be deleted. This is automatic process used by ASP.NET to save server resources. You can also delete complete session or just some variables using ASP.NET server side code. To delete all session data, including session itself, use: Session.Abandon() Calling of Session.Abandon will destroy current session and invoke Session_End event. Notice that session id will still exist after Session.Abandon is called. In case that visitor proceed on some other page, new session will be created with same session id. Session id is deleted when sessoin expires on timeout. To delete only one session variable, use Session.Remove method. For example, to delete variable named "UserTheme", use: Session.Remove("UserTheme"); To remove all keys and values, but keep session active, use: Session.RemoveAll(); As you see, Session.Abandon and Session.RemoveAll are very similar. They both delete all session variables. Difference is that Session.Abandon also destroyes a session, while Session.RemoveAll just clears collection. If InProc mode is used, Session.Abandon will invoke Session_End event. ConclusionAs you see, working with ASP.NET sessions is simple. But, you should take care of few simple tips to avoid possible bugs or maintenance problems in the future. Using of wrapper class can simplify working with sessions, especially if you have large project. If session expires, all its variables are deleted. This could be a problem in some scenarios. If you need to keep your sessions alive while visitor is working on some long task, like filling of long order form or reading a license agreement, see How To Keep ASP.NET Session Alive tutorial. Happy Coding! Tutorial toolbar: Tell A Friend | Add to favorites | Feedback | |