- /// <summary>
- /// Invokes the logic of the middleware.
- /// </summary>
- /// <param name="context">The <see cref="HttpContext"/>.</param>
- /// <returns>A <see cref="Task"/> that completes when the middleware has completed processing.</returns>
- public async Task Invoke(HttpContext context)
- {
- var isNewSessionKey = false;
- Func<bool> tryEstablishSession = ReturnTrue;
- var cookieValue = context.Request.Cookies[_options.Cookie.Name];
- // 解密 cookieValue
- var sessionKey = CookieProtection.Unprotect(_dataProtector, cookieValue, _logger);
- if (string.IsNullOrWhiteSpace(sessionKey) || sessionKey.Length != SessionKeyLength)
- {
- // 生成 36 位随机数
- var guidBytes = new byte[16];
- CryptoRandom.GetBytes(guidBytes);
- sessionKey = new Guid(guidBytes).ToString();
- // 加密 cookieValue
- cookieValue = CookieProtection.Protect(_dataProtector, sessionKey);
- // 设置 Cookie
- var establisher = new SessionEstablisher(context, cookieValue, _options);
- tryEstablishSession = establisher.TryEstablishSession;
- isNewSessionKey = true;
- }
- var feature = new SessionFeature();
- // 创建 Sessin 放入 HttpContext Features
- feature.Session = _sessionStore.Create(sessionKey, _options.IdleTimeout, _options.IOTimeout, tryEstablishSession, isNewSessionKey);
- context.Features.Set<ISessionFeature>(feature);
- try
- {
- // 执行逻辑 (MVC) 之间
- await _next(context);
- // 执行逻辑 (MVC) 之后
- }
- finally
- {
- // 设置 HttpContext Features 为空
- context.Features.Set<ISessionFeature>(null);
- if (feature.Session != null)
- {
- try
- {
- // Commit Session, 把 IDictionary<EncodedKey, byte[]> 中的值放入缓存
- await feature.Session.CommitAsync(context.RequestAborted);
- }
- catch (OperationCanceledException)
- {
- _logger.SessionCommitCanceled();
- }
- catch (Exception ex)
- {
- _logger.ErrorClosingTheSession(ex);
- }
- }
- }
- }
来源: https://www.cnblogs.com/emrys5/p/aspnet-core-session.html