In traditional ASP.NET applications built on the .NET Framework, developers commonly used HttpContext.Current.Session to access session variables from different classes.
However, ASP.NET Core introduced a different approach. It does not support HttpContext.Current. Instead, it provides dependency injection and IHttpContextAccessor to access the current HTTP context.
In this tutorial, we will learn how to create a reusable session helper class in ASP.NET Core and access session variables from controllers and other C# classes.
Configure Session in Program.cs
Program.cs (C# Code)
Before accessing session variables, we need to configure session services in my ASP.NET Core application. Open Program.cs and add the following configuration.
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); builder.Services.AddDistributedMemoryCache(); // Register session services builder.Services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(30); options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; }); builder.Services.AddHttpContextAccessor(); // Register HttpContextAccessor builder.Services.AddScoped<SessionHelper>(); // Register SessionHelper var app = builder.Build(); app.UseHttpsRedirection(); // Configure the HTTP request pipeline. app.UseStaticFiles(); app.UseRouting(); app.UseSession(); // Enable session middleware app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
Here is what the above configurations do.
- AddDistributedMemoryCache() registers an in-memory cache implementation required by session services.
- AddSession() enables session support and configures session timeout.
- AddHttpContextAccessor() allows us to access the current HTTP context through dependency injection.
- AddScoped<SessionHelper>() registers my helper class with a scoped lifetime.
- UseSession() enables session middleware for incoming HTTP requests.
Note: The in-memory cache is suitable for development and single-server deployments. For applications running across multiple servers, use a shared distributed cache such as Redis or SQL Server.
Create a Separate SessionHelper Class
Instead of writing session-related code repeatedly in different controllers and classes, we can create a reusable helper class.
Create a new C# file named SessionHelper.cs.
SessionHelper.cs (C# Code)
using Microsoft.AspNetCore.Http; public class SessionHelper { private readonly IHttpContextAccessor _httpContextAccessor; public SessionHelper(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } private ISession? Session => _httpContextAccessor.HttpContext?.Session; // Set string session value. public void SetString(string key, string value) { Session?.SetString(key, value); } // Get string session value. public string? GetString(string key) { return Session?.GetString(key); } // Set integer session value. public void SetInt(string key, int value) { Session?.SetInt32(key, value); } // Get integer session value. public int? GetInt(string key) { return Session?.GetInt32(key); } // Remove a session variable. public void Remove(string key) { Session?.Remove(key); } // Clear all session variables. public void Clear() { Session?.Clear(); } }
Let's understand how this class works.
- IHttpContextAccessor: Provides access to the current HTTP context.
- Session property: Gets the session associated with the current HTTP request.
- SetString(): Stores a string value in session.
- GetString(): Retrieves a string value from session.
- SetInt(): Stores an integer value in session.
- GetInt(): Retrieves an integer value from session.
- Remove(): Removes a particular session variable.
- Clear(): Removes all session variables.
The advantage of this approach is that we have centralized all session-related operations in one reusable class.
Access Session Variables from a Controller
Now that my helper class is ready, I can inject it into any controller using constructor dependency injection.
HomeController.cs (C# Code)
public class HomeController : Controller
{
private readonly SessionHelper _session;
public HomeController(SessionHelper session)
{
_session = session;
}
public IActionResult Index()
{
// Store session variables.
_session.SetString("UserName", "John");
_session.SetInt("UserId", 101);
return View();
}
public IActionResult Details()
{
// Retrieve session variables.
string? userName = _session.GetString("UserName");
int? userId = _session.GetInt("UserId");
ViewBag.UserName = userName;
ViewBag.UserId = userId;
return View();
}
}In the Index() action, we are storing two session variables.
UserName = John
UserId = 101
In the Details() action, we retrieve these values using my SessionHelper class.
If you have noticed that that we don't need to write the session access code directly inside the controller.
Access Session Variables from Another C# Class
One of the main advantages of creating a separate session helper class is that we can reuse it in other application services.
For example, suppose we have an EmployeeService.cs class that needs to access the currently logged-in user's ID.
We can inject SessionHelper into this class.
public class EmployeeService { private readonly SessionHelper _session; public EmployeeService(SessionHelper session) { _session = session; } public void ProcessEmployee() { // Retrieve session variables. string? userName = _session.GetString("UserName"); int? userId = _session.GetInt("UserId"); // Perform business logic using the current user's information. } }
Register EmployeeService in Program.cs. (See I have created Program.cs in the beginning of this tutorial.)
builder.Services.AddScoped<EmployeeService>();
Now, whenever EmployeeService is injected into a controller or another service, it can access the current request's session variables through SessionHelper.
This makes session management easier and avoids duplicating session access code throughout the application.
Remove or Clear Session Variables
Sometimes, we need to remove a particular session variable or clear the entire session. My helper class already provides methods for both operations.
This is how you remove specific session variable
_session.Remove("UserName");To clear all session variables,
_session.Clear();
For example, when a user logs out, we can clear their session like this.
public IActionResult Logout()
{
_session.Clear();
return RedirectToAction("Index", "Home");
}- Session data is temporary and should not be used as permanent storage. A Session is associated with the browser's session cookie
- Always avoid storing passwords, sensitive information, or large objects in session.
- Do not inject IHttpContextAccessor into a long-running background service to access a user's session.
- Session should be accessed within an active HTTP request.
- For multi-server applications, use a shared distributed cache instead of relying on in-memory session storage.
Conclusion
In ASP.NET Core, we can access session variables from separate C# classes using IHttpContextAccessor and dependency injection. Creating a reusable SessionHelper class makes session management simpler, reduces code duplication, and improves maintainability.
