首先创建ASP.NET CORE Web项目,然后按如下顺序操作。
1.添加nuget程序包:
Microsoft.AspNetCore.Session; Microsoft.AspNetCore.DataProtection.Redis; Microsoft.Extensions.Caching.Redis.Core; Microsoft.AspNetCore.Http; //使用Session时有扩展方法
2.在appsettings.json中添加Redis配置:
1 { 2 "Logging": { 3 "IncludeScopes": false, 4 "LogLevel": { 5 "Default": "Warning" 6 } 7 }, 8 "WebConfig": { 9 "Redis": { 10 "Connection": "127.0.0.1:6379,allowAdmin=true,password=123456,defaultdatabase=5", 11 "InstanceName": "Test_Redis_Session_" 12 }, 13 "SessionTimeOut": "30" //session过期时长,分钟 14 } 15 }
3.在startup.cs类中,按如下例子添加代码:
1 // This method gets called by the runtime. Use this method to add services to the container. 2 public void ConfigureServices(IServiceCollection services) 3 { 4 // Add framework services. 5 services.AddMvc(); 6 7 #region 使用Redis保存Session 8 var redisConn = Configuration["WebConfig:Redis:Connection"]; 9 var redisInstanceName = Configuration["WebConfig:Redis:InstanceName"]; 10 //Session 过期时长分钟 11 var sessionOutTime = Configuration.GetValue<int>("WebConfig:SessionTimeOut", 30); 12 13 var redis = StackExchange.Redis.ConnectionMultiplexer.Connect(redisConn); 14 services.AddDataProtection().PersistKeysToRedis(redis, "DataProtection-Test-Keys"); 15 services.AddDistributedRedisCache(option => 16 { 17 //redis 连接字符串 18 option.Configuration = redisConn; 19 //redis 实例名 20 option.InstanceName = redisInstanceName; 21 } 22 ); 23 #endregion 24 25 //添加Session并设置过期时长 26 services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(sessionOutTime); }); 27 } 28 29 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 30 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 31 { 32 loggerFactory.AddConsole(Configuration.GetSection("Logging")); 33 loggerFactory.AddDebug(); 34 35 36 app.UseSession(); 37 38 if (env.IsDevelopment()) 39 { 40 app.UseDeveloperExceptionPage(); 41 app.UseBrowserLink(); 42 } 43 else 44 { 45 app.UseExceptionHandler("/Home/Error"); 46 } 47 48 app.UseStaticFiles(); 49 50 app.UseMvc(routes => 51 { 52 routes.MapRoute( 53 name: "default", 54 template: "{controller=Home}/{action=Index}/{id?}"); 55 }); 56 }
4.在控制器HomeController中添加:
1 public class HomeController : Controller 2 { 3 public IActionResult Index() 4 { 5 ViewData["UserName"] = this.HttpContext.Session.GetString("UserName"); 6 ViewData["PassWord"] = this.HttpContext.Session.GetString("PassWord"); 7 return View(); 8 } 9 10 11 [HttpPost] 12 public NoContentResult Add(string userName,string pwd) 13 { 14 this.HttpContext.Session.SetString("UserName", userName); 15 16 this.HttpContext.Session.SetString("PassWord", pwd); 17 18 return NoContent(); 19 }
5.在View/Index.cshtml添加如下代码:
1 ………… 2 <form method="post" action="../Home/Add"> 3 <div> 4 <input name="username" id="username" type="text" value="@ViewData["UserName"]" /> 5 <input name="pwd" id="pwd" type="password" value="" /> 6 <input type="submit" value="更新" /> 7 <h1>提交用户名称为:@ViewData["UserName"] 密码:@ViewData["PassWord"]</h1> 8 <a href="javascript:void(0);" onclick="window.location.reload();">刷新显示最新值</a> 9 </div> 10 </form> 11 …………
6.下载Demo