1.添加nuget程序包:redis
Microsoft.Extensions.Caching.Redis
2.在appsettings.json中添加Redis配置:json
"ConnectionRedis": { "Connection": "127.0.0.1:6379,allowAdmin=true,password=123456,defaultdatabase=0", "InstanceName": "SukCore_Redis_Session_", "SessionTimeOut": "20" },
3.在startup.cs類中,ConfigureServices 中添加代碼: cookie
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(); session
注意 app.UseSession(); 必定要在 app.UseMvc 以前 app
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中添加:ide
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 發現一直爲空 還覺得錯了 結果最後發現 要先執行代碼不能先查看ui
附上個人錯誤截圖 看沒有和我同樣傻的 哈哈哈。。。this
錯誤的操做spa
正確的操做 3d