- Understanding How Web Forms Are Processed
- Performing Basic State Management in Web Applications
- Using Cookies
- Using Hidden Fields and Query Strings
- Working with the Session Object
- Working with the Application Object
- Setting Up Global Objects with the global.asax File
- Configuring the Application
Working with the Session Object
Programming with query strings and hidden fields is cumbersome if you need to manipulate more than a trivial amount of state data. Luckily, ASP.NET gives you a better way to store state for each user on the server with the Session object. Every time a new browser hits your ASP.NET application, a new Session object is created for that Web browser. You can store data in the Session object, and it will be available from hit to hit for the same Web browser. Sessions expire after 20 minutes of inactivity by default, although you can change this behavior, as we'll show shortly.
Sessions aren't magic. By default, ASP.NET uses a cookie containing a unique and random ID that it uses to look up the Session object in the ASP.NET server process.
If needed, you can turn off the cookies to instantiate cookieless sessions. You can also offload the storage of session state onto a different server or into a SQL Server database, for "Web farm" scenarios. We'll explain these different session configurations on Day 18, "Configuring Internet Applications."
Adding Data to the Session Object
You can easily add data to the Session object. The line
Session("ValidUser") = true
automatically creates a new variable called ValidUser (if it doesn't exist already) and sets it to true. By default, every variable added to the Session object is of the .NET Object type.
Because variables in the Session object are of type Object, proper programming practice argues that you should cast them to the appropriate type when accessing them:
Dim strUserName As String = CStr(Session("UserName"))
Because Visual basic is very good at automatic data conversions, however, you can usually leave out the explicit cast as shown here:
Dim strUserName As String = Session("UserName")
You might be wondering whether it's appropriate to store large custom objects in Session. The answer is that you should avoid storing large amounts of data in session if possible. You can easily overburden your Web server by storing large amounts of data in Session, especially if your Web site has many users. Databases are a better choice for storing large amounts of state data.
The Session object is of type HTTPSessionState. Its default property is the Item collection, which allows you to access the stored items by using the () notation.
Lifetime of the Session Object
A new session is created once for each new browser that hits your ASP.NET Web site. If a user stops hitting your Web site, his Session will time out after 20 minutes of inactivity, by default.
You can find out how long the Session timeout setting is by using the Timeout method. The following code line prints "20" by default:
<% Response.Write(Session.Timeout.ToString()) %>
You can change the timeout for the Session object by assigning the Timeout property to a certain value, in minutes, such as
Session.Timeout = 5
Removing Objects from the Session Object
Because sessions time out, you don't really need to remove objects from them. However, you can remove objects by using the Session.Remove() method. You also can remove everything in the Session object by using the RemoveAll() method. You might want to use these two methods to conserve Web server resources, especially if you store large objects in Session.
Listing 3.6 shows a page that lets you add and remove strings to the current Session.
Listing 3.6 SessionPopulate.aspx: Adding and Removing Strings from Session State
<%@ language="VB" %> <script runat="server"> Sub AddClicked(Sender As Object, e As EventArgs) Session(Key.Text) = Value.Text End Sub Sub RemoveClicked(Sender As Object, e As EventArgs) Session.Remove(Key.Text) End Sub </script> <html> <body> <h3>Current items in Session</h3> <form method="post" runat="server"> <table border="1"> <tr> <td><b>Item Name</b></td> <td><b>Value</b></td> </tr> <% Dim strSesKeyName As String Dim strSesItem As String Dim i As Integer for i=0 to Session.Count - 1 strSesKeyName = Session.Keys(i) strSesItem = Session(i) Response.Write("<tr><td>" & strSesKeyName & "</td><td>" & _ strSesItem & "</td></tr>") Next %> </table> <br> Key <asp:textbox id="Key" runat="server"/> Value <asp:textbox id="Value" runat="server" /><br> <asp:button text="Add/Modify Key/Value pair" onclick="AddClicked" runat="server" /> <asp:button text="Remove Key" onclick="RemoveClicked" runat="server" /> </form> </body> </html>
You also can kill off a session immediately by using the Abandon() method. As soon as Abandon is called, a new session is created automatically.