.net core 3.0/3.1session持久化redis,session id爲空

  .net core 3.1中將session持久化到redis,從core1.0開始,2.0/2.1,3.0/3.1每次搭建開發框架都由於session的問題搞的頭大,次次踩坑,花了半天時間再次捋了一遍,發出來若是你們有跟我同樣,但願能幫到你,另外若是有幫到你,記得點贊哈!!!redis

1.需引入的庫文件緩存

 1.1:Microsoft.AspNetCore.Http.Extensions,由於.net core中的session默認只能存儲字節,因此引入該庫是爲了解決session存儲字符串session

2.Microsoft.AspNetCore.Session,Microsoft.Extensions.Caching.Redis,針對session擴展app

3.StackExchange.Redis爲redis驅動框架

4.Newtonsoft.Json我本身項目常使用的序列化工具,可根據本身的需求使用ide

項目針對session持久化redis的配置工具

"SessoinConfig": { // Session配置
    "RedisCacheConfig": {
      "ConnectionString": "ip:端口,ssl=false,password=密碼,defaultdatabase=redis庫索引",
      "InstanceName": "自定義實例名"
    },
    "SessionTimeOut": 60 //session過時時長,分鐘
  }

注入實體類:this

    /// <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擴展.net

        /// <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服務添加容器方法ConfigureServicescode

 // 讀取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");
        }

 

 歡迎轉載,轉載請保留出處,哈哈哈

相關文章
相關標籤/搜索