Session management in .Net Core
Asked 2 years 10 months 24 days 10 hours 31 minutes ago, Viewed 2299 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.csservices.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
app.UseSession();
Like
12