How to enable Session in C# ASP.NET Core?

Session is a server-side storage feature in ASP.NET Core that enables you to store user data temporarily across multiple requests. Session data is stored in a dictionary on the server, with each user session identified by a unique SessionId.

The SessionId is stored as a cookie on the client side and sent with every request to maintain the connection between the client and their session data. This cookie is browser-specific and cannot be shared between different browsers. While SessionId cookies persist only for the browser session, the actual session data on the server has a configurable timeout (default: 20 minutes).

Configuring Session in ASP.NET Core

To enable sessions in ASP.NET Core, you need to configure session services in the Startup class. First, add session services in the ConfigureServices method, then add the session middleware in the Configure method.

Session Configuration Flow ConfigureServices AddSession() Configure UseSession() then Session Ready HttpContext.Session available

Basic Configuration Example

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using System;

public class Startup {
    public void ConfigureServices(IServiceCollection services) {
        services.AddMvc();
        services.AddSession(options => {
            options.IdleTimeout = TimeSpan.FromMinutes(60);
            options.Cookie.Name = "MyAppSession";
            options.Cookie.IsEssential = true;
        });
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
        app.UseSession();
        app.UseRouting();
        app.UseEndpoints(endpoints => {
            endpoints.MapControllers();
        });
    }
}

Using Session in Controllers

Once configured, you can access session data through HttpContext.Session. Use SetString() and GetString() methods to store and retrieve string values −

Example

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Text.Json;

public class HomeController : Controller {
    
    [Route("home/index")]
    public IActionResult Index() {
        // Store simple string value
        HttpContext.Session.SetString("product", "laptop");
        
        // Store integer value
        HttpContext.Session.SetInt32("quantity", 2);
        
        // Store complex object as JSON
        var user = new { Name = "John", Age = 30 };
        HttpContext.Session.SetString("user", JsonSerializer.Serialize(user));
        
        ViewBag.Message = "Session data stored successfully";
        return View();
    }
    
    [Route("home/GetSessionData")]
    public IActionResult GetSessionData() {
        // Retrieve session data
        var product = HttpContext.Session.GetString("product");
        var quantity = HttpContext.Session.GetInt32("quantity");
        var userJson = HttpContext.Session.GetString("user");
        
        ViewBag.Product = product ?? "No product found";
        ViewBag.Quantity = quantity ?? 0;
        ViewBag.User = userJson ?? "No user data";
        
        return View();
    }
    
    [Route("home/ClearSession")]
    public IActionResult ClearSession() {
        HttpContext.Session.Clear();
        ViewBag.Message = "Session cleared";
        return View();
    }
}

Session Configuration Options

The AddSession() method accepts various configuration options −

Option Description Default Value
IdleTimeout Time after which session expires if inactive 20 minutes
Cookie.Name Name of the session cookie ".AspNetCore.Session"
Cookie.HttpOnly Prevents client-side script access to cookie true
Cookie.IsEssential Cookie sent even without user consent false

Advanced Configuration Example

public void ConfigureServices(IServiceCollection services) {
    services.AddSession(options => {
        options.IdleTimeout = TimeSpan.FromMinutes(30);
        options.Cookie.Name = "MyApp.SessionId";
        options.Cookie.HttpOnly = true;
        options.Cookie.IsEssential = true;
        options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
    });
}

Session Methods

Common methods available through HttpContext.Session

// String operations
Session.SetString(key, value);
Session.GetString(key);

// Integer operations  
Session.SetInt32(key, value);
Session.GetInt32(key);

// Byte array operations
Session.Set(key, byteArray);
Session.Get(key);

// Session management
Session.Clear();        // Remove all session data
Session.Remove(key);    // Remove specific key

Conclusion

ASP.NET Core sessions provide a convenient way to store user-specific data server-side. Configure sessions by calling AddSession() in ConfigureServices and UseSession() in Configure, then access session data through HttpContext.Session in your controllers.

Updated on: 2026-03-17T07:04:36+05:30

18K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements