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; }
}
2
Answers
In controller, you can do like below:
result:
Update
Create two methods to save and retrieve a class in a session:
To save and retrieve in a session an object of type List, use methods like below:
Result:
You can use objects within your session, but you need to make sure you do a null-check on them (since when not set are defaulting to null)
or set like this: