Home > Back-end >  I'm trying to use sessions to store variables in .net6, but the values are not getting stored
I'm trying to use sessions to store variables in .net6, but the values are not getting stored

Time:05-03

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();

Thats the code that i'm using to set the session variable but that isnt storing the variable, Im 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; }

    }

CodePudding user response:

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:

enter image description here

CodePudding user response:

You can use HttpContext.Session.Set(string key, byte[] value) to achieve. Serialize your class to byte[] first and set session, Then get session and deserialize byte[] to your type

demo

public class Test
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Set session

//For testing convenience,I just hard code here.

List<Test> test = new List<Test>()
    {
        new Test()
        {
            Id = 1,
            Name = "AAA"
        },
        new Test()
        {
            Id = 2,
            Name = "BBB"
        }
    };


IHttpContextAccessor.HttpContext.Session.Set("Test",JsonSerializer.SerializeToUtf8Bytes(test));

Get session

// result is a value of type[], You need deserialize it to your type
var result = IHttpContextAccessor.HttpContext.Session.Get("Test");

var test = JsonSerializer.Deserialize<List<Test>>(result);

result

enter image description here

  • Related