Session and cache
In .net how i can store session and cache please provide some example
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Darshan AdakanePosted Jan 13, 2026, 11:07 AM
Hi Arya
Please find below example for your reference.
1. Storing Session
Session must be explicitly enabled in your
Program.csbefore it can be used.Step A: Configure Program.cs
Step B: Usage in a Controller
2. Storing Cache (Shared/Global)
Use
IMemoryCachefor high-speed, server-side storage of frequently accessed data.Step A: Configure Program.cs
Step B: Usage in a Controller
Comparison:
Hope this helps.
Cynthia SathuragiriPosted Jan 12, 2026, 5:01 AM
1. Session Storage
Session stores data per user across multiple requests.
In ASP.NET Core (Modern approach)
Setup in Program.cs:
var builder = WebApplication.CreateBuilder(args);
// Add session services
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
var app = builder.Build();
app.UseSession(); // Enable session middleware
app.MapControllers();
app.Run();
Using Session in Controller:
public class HomeController : Controller
{
public IActionResult Index()
{
// Store simple values
HttpContext.Session.SetString("Username", "John");
HttpContext.Session.SetInt32("UserId", 123);
// Store complex objects (serialize to JSON)
var user = new { Name = "John", Age = 30 };
HttpContext.Session.SetString("UserObject",
JsonSerializer.Serialize(user));
return View();
}
public IActionResult GetSession()
{
// Retrieve values
var username = HttpContext.Session.GetString("Username");
var userId = HttpContext.Session.GetInt32("UserId");
// Retrieve complex objects
var userJson = HttpContext.Session.GetString("UserObject");
var user = JsonSerializer.Deserialize(userJson);
return Content($"User: {username}, ID: {userId}");
}
}
In ASP.NET Framework (Legacy)
// Store in session
Session["Username"] = "John";
Session["UserId"] = 123;
// Retrieve from session
string username = Session["Username"]?.ToString();
int? userId = Session["UserId"] as int?;
2. Cache Storage
Cache stores data globally for all users, great for performance optimization.
In-Memory Cache (ASP.NET Core)
Setup in Program.cs:
builder.Services.AddMemoryCache();
Using IMemoryCache:
public class ProductService
{
private readonly IMemoryCache _cache;
public ProductService(IMemoryCache cache)
{
_cache = cache;
}
public List GetProducts()
{
string cacheKey = "ProductList";
// Try to get from cache
if (!_cache.TryGetValue(cacheKey, out List products))
{
// If not in cache, fetch from database
products = FetchFromDatabase();
// Set cache options
var cacheOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromMinutes(5))
.SetAbsoluteExpiration(TimeSpan.FromHours(1))
.SetPriority(CacheItemPriority.Normal);
// Store in cache
_cache.Set(cacheKey, products, cacheOptions);
}
return products;
}
public void RemoveCache()
{
_cache.Remove("ProductList");
}
}
Session:
User-specific data
Expires when session ends
Stored per user
Good for: user preferences, shopping carts, authentication tokens
Cache:
Application-wide data
Shared across all users
Configurable expiration
Good for: database query results, API responses, static data
Both help improve performance by reducing database calls and storing frequently accessed data in memory
Mageshwaran RPosted Nov 21, 2019, 10:29 AM
Sanwar RanwaPosted Sep 18, 2019, 3:42 AM