๐Ÿง  ASP.NET State Management & Personalization
Estimated reading: 4 minutes 43 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

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

Or Copy Link

CONTENTS
Scroll to Top