ASP.NET Core 使用Redis存储Session

1. 配置服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public void ConfigureServices(IServiceCollection services)
{


services.AddMvc();

//添加redis
services.AddDistributedRedisCache(options =>
{
options.Configuration = "localhost";

});

//添加session
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(10); //session活期时间
options.Cookie.HttpOnly = true;//设为httponly
});
}

2. 启用Session

1
2
3
4
5
6
7
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//使用session
app.UseSession();

...
}

3. 对Session进行操作

使用 HttpContext.Session来获取Session对象

1
HttpContext.Session.SetString("userid","1000");

坚持技术分享,您的支持将鼓励我继续创作!