Session management in .Net Core

Asked 1 year 8 months 1 day 18 hours 48 minutes ago, Viewed 1802 times

Sessions can be used to pass data between controllers and views. This can be compared to global data in a desktop application. Operations that can be performed on session variables:

Read data.
 if (!string.IsNullOrEmpty(HttpContext.Session.GetString(SessionName)))
 {
     var name = HttpContext.Session.GetString(SessionName);          
 }

 if (!string.IsNullOrEmpty(HttpContext.Session.GetInt32(SessionAge)))
 {
     var age = HttpContext.Session.GetInt32(SessionAge).ToString();         
 }
Set data.
public void setSession()
 {
     HttpContext.Session.SetString("SessionName", "Value");
     HttpContext.Session.SetInt32("SessionAge", 74);
 }
Remove data.

 HttpContext.Session.Remove("SessionName");

Session implementation:

Startup.cs
services.AddDistributedMemoryCache();

services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromSeconds(10);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

app.UseSession();