1.添加nuget程序包:
Microsoft.Extensions.Caching.Redis
2.在appsettings.json中添加Redis配置:
"ConnectionRedis": { "Connection": "127.0.0.1:6379,allowAdmin=true,password=123456,defaultdatabase=0", "InstanceName": "SukCore_Redis_Session_", "SessionTimeOut": "20" },
3.在startup.cs类中,ConfigureServices 中添加代码:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => false; //这里要改为false,默认是true,true的时候session无效 options.MinimumSameSitePolicy = SameSiteMode.None; });
#region 使用Redis保存Session // 这里取连接字符串 自己取吧... ConnectionConfigModel con = ConfigurationManager.GetAppSettings<ConnectionConfigModel>(); services.AddDistributedRedisCache(option => { //redis 连接字符串 option.Configuration = con.ConnectionConfig.ConnectionRedis.Connection; //redis 实例名 option.InstanceName = con.ConnectionConfig.ConnectionRedis.InstanceName; } ); //添加session 设置过期时长分钟 var sessionOutTime = con.ConnectionConfig.ConnectionRedis.SessionTimeOut; services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(Convert.ToDouble(sessionOutTime)); //session活期时间 options.Cookie.HttpOnly = true;//设为httponly }); #endregion }
Configure 中 添加 app.UseSession();
注意 app.UseSession(); 一定要在 app.UseMvc 之前
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { //使用session app.UseSession(); app.UseMvc(routes => { routes.MapRoute( name: "areas", template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
4.在控制器 Controller中添加:
public class HomeController : Controller { [HttpPost] public NoContentResult Add(string userName,string pwd) { this.HttpContext.Session.SetString("UserName", userName); this.HttpContext.Session.SetString("PassWord", pwd); ViewData["UserName"] = this.HttpContext.Session.GetString("UserName"); ViewData["PassWord"] = this.HttpContext.Session.GetString("PassWord"); return NoContent(); }
在调试的过程中遇到一个尴尬的问题 controller中打断点 没有执行session之前 先查看了 session id 发现一直为空 还以为错了 结果最后发现 要先执行代码不能先查看
附上我的错误截图 看没有和我一样傻的 哈哈哈。。。
错误的操作
正确的操作