ASP.NET Core 使用Redis存储Session

前言:Session是我们在web开发中经常使用的对象,它默认是存在本机的,但是在ASP.NET Core中我们可以十分方便的将Session的存储介质改为分布式缓存(Redis)或者数据库(SqlServer)。分布式的缓存可以提高ASP.NET Core 应用的性能和可伸缩性 ,尤其是在托管在云中或服务器场环境中。

使用:ASP.NET Core 已经为我们实现了Redis缓存。

1、配置服务

 1 public void ConfigureServices(IServiceCollection services)
 2 {
 3             
 4 
 5     services.AddMvc();
 6 
 7     //添加redis
 8     services.AddDistributedRedisCache(options =>
 9     {
10         options.Configuration = "localhost";
11                 
12     });
13 
14     //添加session
15     services.AddSession(options =>
16     {
17         options.IdleTimeout = TimeSpan.FromMinutes(10); //session活期时间
18         options.Cookie.HttpOnly = true;//设为httponly
19     });
20 }
 

2.启用session

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

3.对session进行操作

使用 HttpContext.Session来获取Session对象

例:HttpContext.Session.SetString("userid","1000");

运行项目,可以看到redis已经有我们刚刚访问所创建的Session

猜你喜欢

转载自www.cnblogs.com/tianlong/p/9211668.html