User Session Management In ASP.NET Core

Managing user sessions is a critical aspect of web development. In ASP.NET Core, session management helps maintain user state and data across multiple requests. Every web developer should have knowledge of how to manage session(User Session) in the website development. This post , we’ll explore the basics and best practices for user session management in ASP.NET Core, including configuration, usage, and alternatives.

User Session Management In ASP.NET Core

Getting Started

Session management refers to the process of maintaining user data throughout a user's interaction with a web application. This data could include authentication status, user preferences, shopping cart items, etc. Website sessions are commonly stored on the server and referenced by a unique session ID stored in a client-side cookie.

Enable Session in ASP.NET Core

Session state is not enabled by default in ASP.NET Core and must be explicitly configured. If required, the necessary packages may also need to be installed.

Install Required Packages

Make sure your project includes the Microsoft.AspNetCore.Session package. This is typically included in ASP.NET Core web projects. If it is not already present, follow the appropriate steps below to install it.

Using NuGet Package Manager (GUI in Visual Studio)
  1. Right-click on your project in Solution Explorer.
  2. Click Manage NuGet Packages.
  3. Go to the Browse tab.
  4. Search for: Microsoft.AspNetCore.Session
  5. Select it, choose the version (latest is usually fine), and click Install.

Using NuGet Package Manager Console

Open the Package Manager Console in Visual Studio (Tools > NuGet Package Manager > Package Manager Console), then run:

Install-Package Microsoft.AspNetCore.Session

Using .NET CLI

If you're working with the terminal or VS Code:

dotnet add package Microsoft.AspNetCore.Session

Configure Session in ASP.NET Core

User session is confugred in ASP.NET Core using services in Startu.cs or Progam.cs files depending on your project structure. If you are working with .NET 6 or an earlier version, the configuration should be done in the Startu.cs file or If you are working with .NET 7 or later, the configuration should be done in the Progam.cs file

In .NET 6 and earlier:Startu.cs
 public void ConfigureServices(IServiceCollection services)  
 {  
   services.AddDistributedMemoryCache(); // Required for storing session data in memory  
   services.AddSession(options =>  
   {  
     options.IdleTimeout = TimeSpan.FromMinutes(30); // Session timeout  
     options.Cookie.HttpOnly = true;  
     options.Cookie.IsEssential = true;  
   });  
   services.AddControllersWithViews();  
 }  

Enable Middleware
 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
 {  
   if (env.IsDevelopment())  
   {  
     app.UseDeveloperExceptionPage();  
   }  
   app.UseRouting();  
   app.UseSession(); // Add this BEFORE UseEndpoints  
   app.UseAuthentication();  
   app.UseAuthorization();  
   app.UseEndpoints(endpoints =>  
   {  
     endpoints.MapDefaultControllerRoute();  
   });  
 }  

In .NET 7 and Later Version
 var builder = WebApplication.CreateBuilder(args);  
 builder.Services.AddDistributedMemoryCache();  
 builder.Services.AddSession(options =>  
 {  
   options.IdleTimeout = TimeSpan.FromMinutes(30);  
   options.Cookie.HttpOnly = true;  
   options.Cookie.IsEssential = true;  
 });  
 builder.Services.AddControllersWithViews();  
 var app = builder.Build();  
 app.UseSession();  
 app.UseRouting();  
 app.UseAuthorization();  
 app.MapDefaultControllerRoute();  
 app.Run();  

Manage User Session on Website

ASP.NET Core uses controller or middleware to manage session state. It stores session data on the server and tracks users via a cookie called .AspNetCore.Session. Record of is stored in an IDictionary<string, object> format. The below examples show how to fetch and record user session on website.

Record User Sessions On Website

The below code exampe describes how to store user session in ASP.NET Web application, ASP.NET Core sessions store key-value pairs as strings or byte arrays.

Set Session Values
HttpContext.Session.SetString("UserName", "Kailash'sBlogs");  

Set Complex Object
using System.Text.Json;  
 var user = new User { Id = 1, Name = "Alice" };  
 HttpContext.Session.SetString("UserObject", JsonSerializer.Serialize(user));  

Fetch Website Sessions

The below examples show how to fetch data from user session and store in local variable.

Get Session Value
string username = HttpContext.Session.GetString("UserName"); 

Get Complex Object
 string userJson = HttpContext.Session.GetString("UserObject");  
 if (userJson != null)  
 {  
   var user = JsonSerializer.Deserialize<User>(userJson);  
 }  

In the case of complex object, you need to do serialize or deserilize the object for storing and fetching record from user serssion.

Remove Session Values

Remove a Value
HttpContext.Session.Remove("Username"); 

Remove Complex Object
 public static class SessionExtensions  
 {  
   public static void SetObject<T>(this ISession session, string key, T value)  
   {  
     session.SetString(key, JsonSerializer.Serialize(value));  
   }  
   public static T GetObject<T>(this ISession session, string key)  
   {  
     var value = session.GetString(key);  
     return value == null ? default : JsonSerializer.Deserialize<T>(value);  
   }  
 }  

Session Storage Options

By default, sessions use in-memory storage, but you can use:

  • Distributed SQL Server Cache
  • Redis
  • Custom distributed cache providers
Example (using Redis):
 builder.Services.AddStackExchangeRedisCache(options =>  
 {  
   options.Configuration = "localhost";  
   options.InstanceName = "MyApp_";  
 });  
 builder.Services.AddSession();  

Summary

User session management in ASP.NET Core is powerful and flexible. By leveraging built-in session middleware and optionally integrating distributed caching, developers can maintain a seamless and secure user experience across requests. Be mindful of security and scalability as you implement session logic in your applications. I hope this was helpful to you.

Thanks

Kailash Chandra Behera

An IT professional with over 13 years of experience in the full software development life cycle for Windows, services, and web-based applications using Microsoft .NET technologies. Demonstrated expertise in delivering all phases of project development—from initiation to closure—while aligning with business objectives to drive process improvements, competitive advantage, and measurable bottom-line gains. Proven ability to work independently and manage multiple projects successfully. Committed to the efficient and effective development of projects in fast-paced, deadline-driven environments. Skills: Proficient in designing and developing applications using various Microsoft technologies. Total IT Experience: 13+ years

Previous Post Next Post

نموذج الاتصال