ASP.NET Core 好像不能像20年前那样直接使用Session函数,我使用如下方法
1、在NuGet安装以下2个包
2、在Program.cs注册
cs
//注册Session
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(60);
options.Cookie.HttpOnly = false;
});
//注册上下文
builder.Services.AddHttpContextAccessor();
var app = builder.Build();
//启用Session
app.UseSession();
3、在控制器中使用
cs
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly ISession _session; //session对象
private readonly IHttpContextAccessor _contextAccessor; //上下文对象
//构造函数的参数中引用IHttpContextAccessor对象
//再把它和它的Session赋值给本控制器的_contextAccessor和_session
public HomeController(ILogger<HomeController> logger, IHttpContextAccessor contextAccessor)
{
_logger = logger;
_contextAccessor = contextAccessor;
_session = contextAccessor.HttpContext.Session;
}
public IActionResult Index()
{
//然后可以使用_session来添加或者读取需要的变量
_session.SetString("uname", "Jack");
ViewData["uid"] = _session.GetString("uname");
return View();
}
}