.net core 3.1中將session持久化到redis,從core1.0開始,2.0/2.1,3.0/3.1每次搭建開發框架都因為session的問題搞的頭大,次次踩坑,花了半天時間再次捋了一遍,發出來如果大家有跟我一樣,希望能幫到你,另外如果有幫到你,記得點贊哈!!! 1.需引入的庫文件 ...
.net core 3.1中將session持久化到redis,從core1.0開始,2.0/2.1,3.0/3.1每次搭建開發框架都因為session的問題搞的頭大,次次踩坑,花了半天時間再次捋了一遍,發出來如果大家有跟我一樣,希望能幫到你,另外如果有幫到你,記得點贊哈!!!
1.需引入的庫文件
1.1:Microsoft.AspNetCore.Http.Extensions,因為.net core中的session預設只能存儲位元組,所以引入該庫是為瞭解決session存儲字元串
2.Microsoft.AspNetCore.Session,Microsoft.Extensions.Caching.Redis,針對session擴展
3.StackExchange.Redis為redis驅動
4.Newtonsoft.Json我自己項目常使用的序列化工具,可根據自己的需求使用
項目針對session持久化redis的配置
"SessoinConfig": { // Session配置 "RedisCacheConfig": { "ConnectionString": "ip:埠,ssl=false,password=密碼,defaultdatabase=redis庫索引", "InstanceName": "自定義實例名" }, "SessionTimeOut": 60 //session過期時長,分鐘 }
註入實體類:
/// <summary> /// Session緩存配置 /// </summary> public class SessoinConfig { /// <summary> /// session過期時長,分鐘 /// </summary> public int SessionTimeOut { get; set; } /// <summary> /// 實例庫索引 /// </summary> public RedisCacheConfigData RedisCacheConfig { get; set; } } /// <summary> /// Session持久化Redis配置 /// </summary> public class RedisCacheConfigData { /// <summary> /// Redis連接字元串 /// </summary> public string ConnectionString { get; set; } /// <summary> /// Redis實例名稱 /// </summary> public string InstanceName { get; set; } }
IServiceCollection擴展
/// <summary> /// Session持久化至Redis /// </summary> /// <param name="services"></param> /// <param name="Configuration"></param> public static void UseSession(this IServiceCollection services, SessoinConfig sessoinConfig) { services.AddSingleton<IDistributedCache>( serviceProvider => new RedisCache(new RedisCacheOptions { Configuration = sessoinConfig.RedisCacheConfig.ConnectionString, InstanceName = sessoinConfig.RedisCacheConfig.InstanceName })); // 添加Session並設置過期時長 services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(sessoinConfig.SessionTimeOut); }); }
Startup服務添加容器方法ConfigureServices
// 讀取Session配置文件 IConfigurationSection sessionCacheSections = Configuration.GetSection("SessoinConfig"); SessoinConfig sessionCacheConfig = sessionCacheSections.Get<SessoinConfig>(); services.UseSession(sessionCacheConfig);
Startup運行時方法Configure使用Session
// 使用Session app.UseSession();
自定義Session擴展
/// <summary> /// Session擴展 /// </summary> public static class SessionExtensions { /// <summary> /// 添加Session /// </summary> /// <param name="session"></param> /// <param name="key"></param> /// <param name="value"></param> public static void SetObjectAsJson(this ISession session, string key, object value) { session.SetString(key, JsonConvert.SerializeObject(value)); } /// <summary> /// 添加Session /// </summary> /// <param name="session"></param> /// <param name="key"></param> /// <param name="value"></param> public static void SetObjectAsJson<T>(this ISession session, string key, T value) { session.SetString(key, JsonConvert.SerializeObject(value)); } /// <summary> /// 獲取Session /// </summary> /// <typeparam name="T"></typeparam> /// <param name="session"></param> /// <param name="key"></param> /// <returns></returns> public static T GetObjectFromJson<T>(this ISession session, string key) { var value = session.GetString(key); return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value); } /// <summary> /// 刪除Session /// </summary> /// <param name="session"></param> /// <param name="key"></param> public static void RemoveSession(this ISession session, string key) { var value = session.GetString(key); if (value != null) { session.Remove(key); } } }
例如我存儲登錄驗證碼
/// <summary> /// 用戶登錄驗證碼 /// </summary> protected string ValidateCodeData { get { return HttpContext.Session.GetObjectFromJson<string>(LoginValidateCodeSessionKey); } set { HttpContext.Session.SetObjectAsJson<string>(LoginValidateCodeSessionKey, value); } }
/// <summary> /// 獲取驗證碼 /// </summary> /// <returns></returns> public IActionResult ValidateCode() { System.IO.MemoryStream ms = _logic.LoginValidateCode(out string code, 4); ValidateCodeData = code; Response.Body.Dispose(); return File(ms.ToArray(), @"image/png"); }
歡迎轉載,轉載請保留出處,哈哈哈