Session State Overview
Session state enables you to store and retrieve user‑specific data across multiple requests within a web application. ASP.NET provides several session state modes to balance performance, scalability, and durability.
- InProc – stored in the memory of the web server process.
- StateServer – stored in a separate Windows service.
- SQLServer – stored in a SQL Server database.
- Custom – implement
IStateServerProviderfor bespoke storage.
Getting Started
Enabling Session State
<configuration>
<system.web>
<sessionState mode="InProc" timeout="20" cookieless="UseCookies" />
</system.web>
</configuration>
Storing Data
protected void Page_Load(object sender, EventArgs e)
{
// Store a value
Session["UserName"] = "Alice";
// Retrieve a value
string name = Session["UserName"] as string;
}
Removing Data
// Remove a single item
Session.Remove("UserName");
// Clear all items
Session.Clear();
// Abandon the session entirely
Session.Abandon();
Best Practices
- Keep session data small – store only essential identifiers.
- Never store large objects or sensitive data without encryption.
- Prefer read‑only scenarios; modify session data sparingly.
- Use
Session.IsNewSessionto detect session timeouts. - Consider
SessionStateMode=SQLServerfor web farms.
Reference
| Class / Interface | Description |
|---|---|
HttpSessionState | Provides access to session values. |
SessionStateMode | Enumeration for session storage modes. |
IHttpSessionState | Interface for custom session implementations. |
SessionStateUtility | Helper methods for session state management. |