I'm trying to use sessions to store variables in .net6, I already configured program.cs but the session still not storing the values, using .net6 core with c#.
using Microsoft.EntityFrameworkCore;
using nsaprojeto.Data;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<ApplicationDbContext>(options =>options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")
));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseSession();
app.MapControllerRoute(
name: "default",
pattern: "{controller=L_AccessPoint}/{action=Filtros1}");
app.Run();
That's the code that I'm using to set the session variable, but that isn't storing the variable, I'm doing something wrong, or forgetting something.
HttpContext.Session.SetString("adad", "dwdwwww");
EDIT: I have the following object and I need to store that in the session variables, is that possible to do?
public class L_AccessPoint
{
public string ap_name { get; set; }
public short? zone_id { get; set; }
public decimal? latitude { get; set; }
public decimal? longitude { get; set; }
public string ap_eth_mac { get; set; }
public DateTime ts { get; set; }
public short ap_id { get; set; }
public Byte? type { get; set; }
public bool Active { get; set; }
}
In controller, you can do like below:
public class HomeController : Controller
{
public IActionResult Index()
{
ISession session = HttpContext.Session;
session.SetString("Username", "ffff");
return View();
}
public IActionResult Privacy()
{
ISession session = HttpContext.Session;
string username = session.GetString("Username");
return View();
}
}
result:
Update
Create two methods to save and retrieve a class in a session:
public static class SessionExtensions
{
public static void Set<T>(this ISession session, string key, T value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static T Get<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
}
}
To save and retrieve in a session an object of type List, use methods like below:
public class HomeController : Controller
{
public IActionResult Index()
{ // your list object
List<L_AccessPoint> myList = new List<L_AccessPoint>
{
new L_AccessPoint(){ ap_name = "Sylvester", zone_id=8,latitude=1, longitude=1},
new L_AccessPoint(){ ap_name = "Whiskers", zone_id=2,latitude=1, longitude=1 },
new L_AccessPoint(){ ap_name = "Sasha", zone_id=14 ,latitude=1, longitude=1}
};
// To set value in session
HttpContext.Session.Set<List<L_AccessPoint>>("obj", myList);
return View();
}
public IActionResult Privacy()
{
// To Get Value from Session
List<L_AccessPoint> classCollection = HttpContext.Session.Get<List<L_AccessPoint>>("obj");
return View();
}
}
Result: