[英]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.