Understanding Session Management in ASP.NET Core

← Prev

When we browse a website, we often move between different pages. But HTTP is a stateless protocol, which means each request is treated independently by the server.

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.

Understanding Session Management in ASP.NET Core How an application remembers users across multiple requests 1. USERVisits the website2. BROWSERSends requests3. SERVERASP.NET Core App4. SESSIONStores user dataOpenRequestSaveSession ID CookieExample: Data Stored in SessionUserNameArunUserId101CartCount3 ItemsWhy Do We Need Sessions?• Remember logged-in user information• Maintain shopping cart details• Share data across multiple requests Session helps ASP.NET Core remember temporary user-specific data between requests

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,

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.

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.

← Previous