[asp.net core 源碼分析] 01 - Session

来源:https://www.cnblogs.com/emrys5/archive/2018/08/09/aspnet-core-session.html
-Advertisement-
Play Games

1、Session文檔介紹 2、Session簡單應用 2.1、在Startup類的ConfigureServices方法中添加 因為Session的服務端存儲需要緩存,所以需要引入.Net core的緩存DistributedMemoryCache; 2.2、在Startup類的Configure ...


 1、Session文檔介紹

  1. 毋庸置疑學習.Net core最好的方法之一就是學習微軟.Net core的官方文檔;https://docs.microsoft.com/zh-cn/aspnet/core
  2. .Net core Session的官方文檔 https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/app-state
  3. .Net core Session Github源碼 https://github.com/aspnet/Session

2、Session簡單應用

2.1、在Startup類的ConfigureServices方法中添加

services.AddDistributedMemoryCache();
services.AddSession();

因為Session的服務端存儲需要緩存,所以需要引入.Net core的緩存DistributedMemoryCache;

2.2、在Startup類的Configure方法中添加

app.UseSession();

2.3、使用(存儲和獲取)

// 存儲
HttpContext.Session.Set("LoginId", System.Text.Encoding.Default.GetBytes("666"));

// 獲取
HttpContext.Session.TryGetValue("LoginId", out byte[] byteLoginId);
var loginId = System.Text.Encoding.Default.GetString(byteLoginId); // LoginId="666";

 3、源碼分析圖

 

 

 

 4、源碼分析

4.1、程式載入

4.1.1、在ConfigureServices中添加分散式緩存,services.AddDistributedMemoryCache();

微軟官方建議使用AddDistributedMemoryCache,當然也可以使用AddMemoryCache、AddDistributedRedisCache、AddDistributedSqlServerCache或者自定義緩存也是可以的;

如果是分散式系統或者SSO單點登錄,建議使用分散式的緩存,不要使用AddMemoryCache;

緩存的官方文檔 https://docs.microsoft.com/zh-cn/aspnet/core/performance/caching/memory

4.1.2、在ConfigureServices中添加AddSession;

 1 public static IServiceCollection AddSession(this IServiceCollection services)
 2 {
 3     if (services == null)
 4     {
 5         throw new ArgumentNullException(nameof(services));
 6     }
 7 
 8     services.AddTransient<ISessionStore, DistributedSessionStore>();
 9     services.AddDataProtection();
10     return services;
11 }
12  
13 public static IServiceCollection AddSession(this IServiceCollection services, Action<SessionOptions> configure)
14 {
15     if (services == null)
16     {
17         throw new ArgumentNullException(nameof(services));
18     }
19 
20     if (configure == null)
21     {
22         throw new ArgumentNullException(nameof(configure));
23     }
24 
25     services.Configure(configure);
26     services.AddSession();
27 
28     return services;
29 }
View Code

AddSession為IServiceCollection的擴展方法,有1個重載(傳入Session的設置,使用services.Configure(configure),載入設置);

services.AddDataProtection()註入數據加密解密DataProtection(),在加密解密SessionKey時使用;

services.AddTransient<ISessionStore, DistributedSessionStore>();註入DistributedSessionStore,其中的Create 方法用做創建Session,調用Create方法時執行new DistributedSession();  DistributedSession類中包含了對IDictionary<EncodedKey, byte[]>的增刪改查;

 4.1.3、在Configure中UseSession

 1 public static IApplicationBuilder UseSession(this IApplicationBuilder app)
 2 {
 3     if (app == null)
 4     {
 5         throw new ArgumentNullException(nameof(app));
 6     }
 7 
 8     return app.UseMiddleware<SessionMiddleware>();
 9 }
10 
11 
12 public static IApplicationBuilder UseSession(this IApplicationBuilder app, SessionOptions options)
13 {
14     if (app == null)
15     {
16         throw new ArgumentNullException(nameof(app));
17     }
18     if (options == null)
19     {
20         throw new ArgumentNullException(nameof(options));
21     }
22 
23     return app.UseMiddleware<SessionMiddleware>(Options.Create(options));
24 }
View Code

UseSession為IApplicationBuilder的擴展方法,也有1個重載,同樣也是載入Session的設置,使用Options.Create(options)結合中間件載入設置;

關於中間件可以參考文檔 https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware

SessionMiddleware.cs為Session的中間件;其中包含Session的核心代碼,操作MVC之前和之後的代碼都在中間件中;

4.2、SessionMiddleware.cs類解析

 在SessionMiddleware中一個非同步方法Invoke;主要邏輯中包含了註釋,應該很好理解;

 1   /// <summary>
 2         /// Invokes the logic of the middleware.
 3         /// </summary>
 4         /// <param name="context">The <see cref="HttpContext"/>.</param>
 5         /// <returns>A <see cref="Task"/> that completes when the middleware has completed processing.</returns>
 6         public async Task Invoke(HttpContext context)
 7         {
 8             var isNewSessionKey = false;
 9             Func<bool> tryEstablishSession = ReturnTrue;
10             var cookieValue = context.Request.Cookies[_options.Cookie.Name];
11 
12             // 解密cookieValue
13             var sessionKey = CookieProtection.Unprotect(_dataProtector, cookieValue, _logger);
14             if (string.IsNullOrWhiteSpace(sessionKey) || sessionKey.Length != SessionKeyLength)
15             {
16 
17                 // 生成36位隨機數
18                 var guidBytes = new byte[16];
19                 CryptoRandom.GetBytes(guidBytes);
20                 sessionKey = new Guid(guidBytes).ToString();
21 
22                 // 加密cookieValue
23                 cookieValue = CookieProtection.Protect(_dataProtector, sessionKey);
24 
25                 // 設置Cookie
26                 var establisher = new SessionEstablisher(context, cookieValue, _options);
27                 tryEstablishSession = establisher.TryEstablishSession;
28                 isNewSessionKey = true;
29             }
30 
31             var feature = new SessionFeature();
32             // 創建Sessin放入 HttpContext Features
33             feature.Session = _sessionStore.Create(sessionKey, _options.IdleTimeout, _options.IOTimeout, tryEstablishSession, isNewSessionKey);
34             context.Features.Set<ISessionFeature>(feature);
35 
36             try
37             {
38                 // 執行邏輯(MVC)之間
39                 await _next(context);
40                 // 執行邏輯(MVC)之後
41             }
42             finally
43             {
44                 // 設置HttpContext Features為空
45                 context.Features.Set<ISessionFeature>(null);
46 
47                 if (feature.Session != null)
48                 {
49                     try
50                     {
51                         // Commit Session,把 IDictionary<EncodedKey, byte[]>中的值放入緩存
52                         await feature.Session.CommitAsync(context.RequestAborted);
53                     }
54                     catch (OperationCanceledException)
55                     {
56                         _logger.SessionCommitCanceled();
57                     }
58                     catch (Exception ex)
59                     {
60                         _logger.ErrorClosingTheSession(ex);
61                     }
62                 }
63             }
64         }
View Code

 4.3、DistributedSession.cs 類解析

在SessionMiddleware Invoke方法中,可以看到創建Session最終執行的是new DistributedSession();

此類就不做過多的介紹了,主要就是對IDictionary<EncodedKey, byte[]>增刪改查,序列化值、從緩存中Load數據和把數據放入緩存中;

代碼過多就不放置博客上,可移至github :https://github.com/aspnet/Session/blob/master/src/Microsoft.AspNetCore.Session/DistributedSession.cs

5、總結

1、在asp.net core中Session的代碼還是比較簡單的,運用操作也比較簡單;

2、可以清楚的理解asp.net core中Session的原理;

3、可以學習其他生產隨機數的方法;

4、可以學習在中間件中怎麼運用設置(Options.Create(options)、services.Configure(configure));

5、知道了中間件的簡單運用;

6、學寫了Httpcontext Features 的簡單運用,關於 HttpContext可以直接使用Session(HttpContext.Session)在講asp.net core http時會詳細介紹;

7、簡單知道了對於緩存的獲取和增加;

8、下一篇將分析 .net core configuration,敬請關註;

9、記得推薦評論,或者可以留言希望分析哪部分asp.net core的源碼


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一、JDBC常用類和介面 JDBC(Java DataBase Connectivity,java資料庫連接)是一種用於執行SQL語句的Java API。JDBC是Java訪問資料庫的標準規範,可以為不同的關係型資料庫提供統一訪問,它由一組用Java語言編寫的介面和類組成。 JDBC與資料庫驅動的關 ...
  • 最近一些學習Java的小伙伴,向我請教了一些關於Java圖形化界面的問題,以下就是我對Java圖形化界面的一些總結。 一:為何J Frame無法顯示添加的顏色 public class Login extends JFrame{ public Login(){ this.setLayout(null ...
  • Demo: hello_pycharm 根目錄文件:hello_pycharm [__init__.py __pycache__ settings.py urls.py wsgi.py] App:hello [admin.py apps.py __init__.py migrations model ...
  • GIL應該是面試的一個常考題,什麼是GIL? GIL的全程是Global Interpre Lock(全局解釋器鎖)。 不是Python中有GIL,而是CPython中有全局解釋器鎖。(JPython中沒有GIL) GIL是一個互斥鎖,CPython在執行多線程的時候並不是線安全的,為了程式的安全性 ...
  • 電腦技術的演進過程 1946-1981年 電腦系統結構時代(35年) 解決電腦能力的問題 1981-2008年 網路和視窗時代(27年) 解決交互問題 2008-2016年 複雜信息系統時代(8年) 解決數據問題 2016- 人工智慧時代 解決人類的問題 編程語言有哪些呢? 編程語言的種類錯綜 ...
  • python創始人:Guido Van Rossm (荷蘭人) python的官網:https://www.python.org ...
  • 目錄 1. 線程的實現 線程的三種實現方式 Java線程的實現與調度 2. 線程安全 Java的五種共用數據 保證線程安全的三種方式 前言 本篇博文主要是是在Java記憶體模型的基礎上介紹Java線程更多的內部細節,但不是簡單的代碼舉例,更多的是一些理論概念,可以說是對自己的一種理論知識的補充 註:建 ...
  • 加QQ群:838197940免費領取! 【Python參考書籍】 入門讀物 1.《Python基礎教程》(Beginning Python From Novice to Professional)2.《Python學習手冊》(Learning Python)3.《Python編程》(Programm ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...