private void Load() { if (!_loaded) { try { var data = _cache.Get(_sessionKey); if (data != null) { Deserialize(new MemoryStream(data)); } else if (!_isNewSessionKey) { _logger.AccessingExpiredSession(_sessionKey); } _isAvailable = true; } catch (Exception exception) { _logger.SessionCacheReadException(_sessionKey, exception); _isAvailable = false; _sessionId = string.Empty; _sessionIdBytes = null; _store = new NoOpSessionStore(); } finally { _loaded = true; } } }
/// <summary> /// Initializes a new instance of <see cref="DistributedSession"/>. /// </summary> /// <param name="cache">The <see cref="IDistributedCache"/> used to store the session data.</param> /// <param name="sessionKey">A unique key used to lookup the session.</param> /// <param name="idleTimeout">How long the session can be inactive (e.g. not accessed) before it will expire.</param> /// <param name="ioTimeout"> /// The maximum amount of time <see cref="LoadAsync(CancellationToken)"/> and <see cref="CommitAsync(CancellationToken)"/> are allowed take. /// </param> /// <param name="tryEstablishSession"> /// A callback invoked during <see cref="Set(string, byte[])"/> to verify that modifying the session is currently valid. /// If the callback returns <see langword="false"/>, <see cref="Set(string, byte[])"/> throws an <see cref="InvalidOperationException"/>. /// <see cref="SessionMiddleware"/> provides a callback that returns <see langword="false"/> if the session was not established /// prior to sending the response. /// </param> /// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param> /// <param name="isNewSessionKey"><see langword="true"/> if establishing a new session; <see langword="false"/> if resuming a session.</param> public DistributedSession( IDistributedCache cache, string sessionKey, TimeSpan idleTimeout, TimeSpan ioTimeout, Func <bool> tryEstablishSession, ILoggerFactory loggerFactory, bool isNewSessionKey) { if (cache == null) { throw new ArgumentNullException(nameof(cache)); } if (string.IsNullOrEmpty(sessionKey)) { throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(sessionKey)); } if (tryEstablishSession == null) { throw new ArgumentNullException(nameof(tryEstablishSession)); } if (loggerFactory == null) { throw new ArgumentNullException(nameof(loggerFactory)); } _cache = cache; _sessionKey = sessionKey; _idleTimeout = idleTimeout; _ioTimeout = ioTimeout; _tryEstablishSession = tryEstablishSession; // When using a NoOpSessionStore, using a dictionary as a backing store results in problematic API choices particularly with nullability. // We instead use a more limited contract - `IDistributedSessionStore` as the backing store that plays better. _store = new DefaultDistributedSessionStore(); _logger = loggerFactory.CreateLogger <DistributedSession>(); _isNewSessionKey = isNewSessionKey; }