简体   繁体   English

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

[英]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, I already configured program.cs but the session still not storing the values, using .net6 core with c#.我正在尝试使用会话在 .net6 中存储变量,我已经配置了 program.cs 但 session 仍然没有存储值,使用 .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();

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.那是我用来设置 session 变量的代码,但它没有存储变量,我做错了什么,或者忘记了什么。

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?编辑:我有以下 object 并且我需要将其存储在 session 变量中,这可能吗?

    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:在 controller 中,您可以这样做:

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:创建两个方法以在 session 中保存和检索 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);
        }
    }

To save and retrieve in a session an object of type List, use methods like below:要在类型为 List 的 session 和 object 中保存和检索,请使用如下方法:

 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:结果:

在此处输入图像描述

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)您可以在 session 中使用对象,但您需要确保对它们进行空检查(因为未设置时默认为空)

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

or set like this:或者这样设置:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 .NET6 与 Visual Studio for Mac M1 不兼容,我可以为 xamarin 使用什么? - .NET6 not compatible with Visual Studio for Mac M1, what can I use for xamarin? 我正在尝试使用 switch case 来显示存储在类中的数据 - I'm trying to use switch case to display data stored in a class 如何在 .net6 中使用默认值初始化数据库 - How do I initialize database with default values in .net6 从 .net4.8 升级后 .net6 中的会话 - Sessions in .net6 after upgrading from .net4.8 信任其他 CA 并在 net6 MAUI 解决方案中使用 Android 证书存储 - Trust additional CAs and make use of the Android certificate store in a net6 MAUI solution 如何在 .NET5 或 .Net6 中使用 UIAutomation - How to use UIAutomation in .NET5 or .Net6 如何将 CORS 与 .NET6 最小 API 一起使用? - How to use CORS with .NET6 minimal APIs? 我试图通过调用存储过程来填充列表框-仅获取空值 - I'm attempting to populate a listbox by calling a stored procedure - only getting null values 我如何在 Net6 中的程序中使用 DbInizializer - How can I DbInizializer in Program in Net6 我没有通过此存储过程得到正确的结果 - I'm not getting the right result with this store procedure
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM