我正在尝试使用会话在 .net6 中存储变量,但未存储值

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

我正在尝试使用会话在 .net6 中存储变量,我已经配置了 program.cs 但是会话仍然没有存储值,使用 .net6 核心和 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();

这是我用来设置会话变量的代码,但它没有存储变量,我做错了什么,或者忘记了什么。

HttpContext.Session.SetString("adad", "dwdwwww");

编辑: 我有以下对象,我需要将其存储在会话变量中,可以吗?

    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; }

    }

在控制器中,您可以执行以下操作:

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

    
}

结果:

更新

创建两个方法来在会话中保存和检索 class:

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

要在会话中保存和检索 List 类型的对象,请使用如下方法:

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

结果:

您可以在会话中使用对象,但您需要确保对它们执行 null-check(因为未设置时默认为空)

var accessPoint = _contextAccessor.HttpContext.Session.Get<I_AccessPoint>("mykey");
// accessPoint = null when not set

或者这样设置:

 _contextAccessor.HttpContext.Session.Set<I_AccessPoint>("mykey", objectOfAccessPoint);