So, how does a website remember who we are as we navigate from one page to another? This is where Session Management comes into play.
The infographic below illustrates how session management works in ASP.NET Core.
What is Session Management?
In simple terms, session management is a technique used to store and maintain user-specific information across multiple HTTP requests.
For example, after a user logs in, an application may need to remember their User ID, username, or other temporary information while they navigate through the website.
Instead of asking the user for this information on every page, we can store it in a session.
How Does a Session Work?
When a user visits a website, the server creates or identifies a session and associates it with a session cookie stored in the user's browser.
On subsequent requests, the browser sends this cookie back to the server, allowing the application to identify the corresponding session.
For example, a session might contain,
- UserId: 101
- UserName: Arun
- Email: arun@example.com
The application can retrieve these values whenever they are needed during the session.
Why Do We Need Session Management?
Session management is useful for several scenarios.
- User Login: Remember information about the currently logged-in user.
- Shopping Cart: Temporarily maintain shopping cart information.
- User Preferences: Store temporary user-specific settings.
- Multi-step Forms: Preserve information while users move between form steps.
Session Management in ASP.NET Core
ASP.NET Core provides built-in session support through HttpContext.Session. For example, you can store a username like this:
HttpContext.Session.SetString("UserName", "Arun");Note: The method name and arguments are exactly the same in both C# and VB.NET.
And later, retrieve the value like this:
C#
string? userName = HttpContext.Session.GetString("UserName");VB.NET
Dim userName As String = HttpContext.Session.GetString("UserName")💡 ASP.NET Core also allows us to create reusable helper classes using dependency injection, making session management easier across controllers and other application services.
Conclusion
Session management helps web applications remember user-specific information across multiple requests. ASP.NET Core provides built-in session support, making it easier to manage temporary user data and build interactive web applications.
