Step-by-Step: How to Enable Session in .NET Core

๐Ÿ“– Overview

Sessions in ASP.NET Core allow you to persist user-specific data across multiple HTTP requests. Whether you're tracking login state, temporary selections, or user preferences, sessions offer a simple and effective way to store short-term data on the server side.

This guide is ideal for:

  • Developers new to ASP.NET Core sessions
  • Anyone migrating from classic ASP.NET
  • .NET 6+ users following minimal hosting model


๐Ÿ“ฆ 1. Add the Required NuGet Package

If you're not using the default SDK (Microsoft.AspNetCore.App), manually install the session package:

dotnet add package Microsoft.AspNetCore.Session

๐Ÿ› ️ 2. Configure Services in Program.cs

Register memory cache and session services in the DI container:

var builder = WebApplication.CreateBuilder(args);

// In-memory cache for session storage
builder.Services.AddDistributedMemoryCache();

// Register session services
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(30);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true; // Required for GDPR
});

builder.Services.AddControllersWithViews(); // Or AddRazorPages()

๐Ÿ’ก Note: Sessions rely on a cookie (.AspNetCore.Session) to track the client — cookies must be enabled in the browser.

๐Ÿš€ 3. Use Session Middleware

Enable session in the request pipeline before mapping routes:

var app = builder.Build();

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseSession(); // Enable session support

app.UseAuthorization();

app.MapControllers(); // Or app.MapRazorPages()

app.Run();

๐Ÿงช 4. Set and Get Session Values in a Controller

You can set and retrieve session values using HttpContext.Session. Here's a basic example:

using Microsoft.AspNetCore.Http;

public class HomeController : Controller
{
    public IActionResult Index()
    {
        // Store a string in session
        HttpContext.Session.SetString("username", "john.doe");

        // Retrieve it later
        string name = HttpContext.Session.GetString("username");

        ViewBag.Name = name;
        return View();
    }
}

๐Ÿงฑ Working with Complex Objects

Since sessions only support byte arrays or strings, use JSON serialization for complex data:

// Store object
HttpContext.Session.SetString("cart", JsonSerializer.Serialize(cartObject));

// Retrieve object
var cart = JsonSerializer.Deserialize<Cart>(
    HttpContext.Session.GetString("cart"));

✅ Don't forget to add using System.Text.Json; and your model class (e.g., Cart).

๐Ÿ“Œ 5. Important Notes

  • Sessions use a browser cookie named .AspNetCore.Session for tracking.
  • In-memory session storage is great for development or single-server apps.
  • Use Redis, SQL Server, or other distributed caches for load-balanced or production scenarios.
  • Set Cookie.IsEssential = true to ensure compliance with GDPR, even if the user declines non-essential cookies.
  • Session data may be lost on browser restart or timeout.

✅ Summary Table

Step Description
1. Add Package Install Microsoft.AspNetCore.Session
2. Configure Services Add AddDistributedMemoryCache() and AddSession()
3. Use Middleware Call app.UseSession() before route mapping
4. Access Session Use SetString() / GetString() in controllers or pages

๐Ÿ”— What’s Next?

Here are some helpful links and next steps:

๐Ÿ’ก Final Thoughts

Enabling session support in ASP.NET Core is straightforward, but you must treat session data carefully — especially when working with user identities, preferences, or cart information.

For production environments:

  • Avoid InMemory session storage.
  • Prefer Redis or SQL Server with proper expiration strategies.
  • Always validate and sanitize data from sessions, just like any other user input.

Comments

Popular posts from this blog

Debouncing & Throttling in RxJS: Optimizing API Calls and User Interactions

Promises in Angular

Comprehensive Guide to C# and .NET Core OOP Concepts and Language Features