๐Ÿง  ASP.NET State Management & Personalization
Estimated reading: 4 minutes 446 views

ASP.NET Session vs Classic ASP โ€“ Store and Retrieve State with C#

Introduction โ€“ Why Use Session in ASP.NET?

Web applications are stateless by natureโ€”meaning, they forget user data between page requests. Thatโ€™s where Session comes in.

ASP.NET Session lets you store user-specific data on the server, like:

  • Logged-in user info
  • Shopping cart items
  • Temporary form values
  • User roles or preferences

In this guide, you’ll learn:

  • What Session state is and how it works
  • How to store and retrieve data using ASP.NET Session
  • Difference between Classic ASP and ASP.NET Session
  • Complete code examples with explanations and output

ASP.NET Session Use โ€“ Basic Structure

ActionC# ASP.NET Code
Store valueSession["key"] = value;
Retrieve valuevar value = Session["key"];
Remove valueSession.Remove("key");
Clear allSession.Clear();
End sessionSession.Abandon();

Example 1: Storing and Displaying Username

Markup File โ€“ SessionDemo.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SessionDemo.aspx.cs" Inherits="SessionDemo.SessionDemo" %>

<html>
<body>
  <form id="form1" runat="server">
    <h3> ASP.NET Session Example</h3>

    <asp:Label ID="lblPrompt" runat="server" Text="Enter your name:" /><br />
    <asp:TextBox ID="txtName" runat="server" /><br /><br />

    <asp:Button ID="btnSave" runat="server" Text="Save to Session" OnClick="btnSave_Click" /><br /><br />

    <asp:Label ID="lblGreeting" runat="server" Font-Bold="true" ForeColor="Blue" />
  </form>
</body>
</html>

Code-Behind โ€“ SessionDemo.aspx.cs

public partial class SessionDemo : System.Web.UI.Page
{
    protected void btnSave_Click(object sender, EventArgs e)
    {
        // Save input to session
        Session["UserName"] = txtName.Text;

        // Retrieve from session and display
        lblGreeting.Text = "Welcome, " + Session["UserName"];
    }
}

Output:

[Enter your name: _________]  [Save to Session]
โ†’ Welcome, Vaibhav

Name is stored on the server and can be used on other pages.


Example 2: Access Session on Another Page

Page 2 โ€“ Greeting.aspx

<asp:Label ID="lblHello" runat="server" />
protected void Page_Load(object sender, EventArgs e)
{
    lblHello.Text = "Hello again, " + Session["UserName"];
}

Works across pages. No form resubmission required.


Classic ASP vs ASP.NET Session โ€“ Key Differences

FeatureClassic ASPASP.NET Web Forms
SyntaxSession("key") = valueSession["key"] = value;
LanguageVBScriptC# / VB.NET
State TypeServer-SideServer-Side
Session Timeout20 mins default20 mins default (configurable)
Clear SessionSession.Abandon()Session.Abandon()
Object SupportStores strings onlyCan store any object (int, List<>)
Strong Typing No Yes

Additional Session Features in ASP.NET

TaskCode Example
Check if key existsif(Session["UserName"] != null)
Convert to string safelyConvert.ToString(Session["UserName"])
Set timeout (in web.config)
<sessionState timeout="30" />

| Remove specific item | Session.Remove("UserName"); |
| Clear all session data | Session.Clear(); |


Summary โ€“ Recap & Takeaways

ASP.NET Session State allows you to securely and temporarily store data for each user while they browse your application.

Key Learnings:

  • Use Session["key"] to store or retrieve any object per user
  • Data persists across pages until timeout or session end
  • More powerful and object-oriented than Classic ASP session
  • Great for storing login info, carts, and temporary settings
  • Use Session.Abandon() to logout or reset

Sessions are stored server-side, so no user can see or manipulate them from the browser.


Frequently Asked Questions (FAQs)


Where is ASP.NET Session stored by default?
In server memory (InProc). It can also be stored in SQL Server, State Server, or Custom Provider.


How long does Session last?
Default is 20 minutes of inactivity. This can be configured in web.config.


Can I store a List or DataTable in Session?
Yes! You can store complex objects:

Session["Cart"] = new List<string> { "Item1", "Item2" };

Can Classic ASP and ASP.NET share session state?
Not directly. Youโ€™d need a shared database or cookies to bridge session data between the two.


How do I logout and destroy session completely?
Use:

Session.Clear();  // Clears all keys
Session.Abandon(); // Ends session and ID

Share Now :
Share

๐Ÿ” ASP.NET โ€“ Session (merged with Classic ASP Session)

Or Copy Link

CONTENTS
Scroll to Top