Session 是保存用戶和 Web 應用的會話狀態的一種方法,ASP.NET Core 提供了一個用於管理會話狀態的中間件。在本文中我將會簡單介紹一下 ASP.NET Core 中的 Session 的使用方法。html
nuget 添加引用 Microsoft.AspNetCore.Session redis
ession 是基於 IDistributedCache 構建的,因此必須引用一種 IDistributedCache 的實現,ASP.NET Core 提供了多種 IDistributedCache 的實現 (Redis、SQL Server、In-memory) sql
services.AddDistributedMemoryCache();
services.AddSession();
nuget 添加引用 Microsoft.Extensions.Caching.SqlServer數據庫
SqlServerCache實現容許分佈式緩存使用SQL Server數據庫做爲其後備存儲。要建立SQL Server表,您可使用sql-cache工具,該工具將使用您指定的名稱和模式建立一個表。json
要使用sql-cache工具,請添加SqlConfig.Tools
到.csproj文件的<ItemGroup>
元素並運行dotnet恢復。緩存
<ItemGroup> <DotNetCliToolReference Include="Microsoft.Extensions.Caching.SqlConfig.Tools" Version="1.0.0-msbuild3-final" /> </ItemGroup>
經過運行如下命令來測試SqlConfig.Tools服務器
C:\DistCacheSample\src\DistCacheSample>dotnet sql-cache create --help
sql-cache工具將顯示用法,選項和命令幫助,如今你能夠建立表到sql server中,運行「sql-cache create」命令:session
C:\DistCacheSample\src\DistCacheSample>dotnet sql-cache create "Data Source=(localdb)\v11.0;Initial Catalog=DistCache;Integrated Security=True;" dbo TestCache info: Microsoft.Extensions.Caching.SqlConfig.Tools.Program[0] Table and index were created successfully.
建立的表格具備如下架構:架構
注意的ConnectionString
(以及可選地,SchemaName
和TableName
)一般應該被存儲的源控制(如UserSecrets)之外,由於它們可能包含憑證。app
像全部的緩存實現同樣,你的應用程序應該使用一個實例來獲取和設置緩存值IDistributedCache
,而不是SqlServerCache
。該示例SqlServerCache
在Production
環境中實現(所以已配置ConfigureProductionServices
)。
// Microsoft SQL Server implementation of IDistributedCache. // Note that this would require setting up the session state database. services.AddDistributedSqlServerCache(o => { o.ConnectionString = "Server=.;Database=ASPNET5SessionState;Trusted_Connection=True;"; o.SchemaName = "dbo"; o.TableName = "Sessions"; }); services.AddSession();
nuget 添加引用 Microsoft.Extensions.Caching.Redis
Redis是一款開源的內存數據存儲,一般用做分佈式緩存。您能夠在本地使用它,而且能夠爲Azure託管的ASP.NET Core應用程序配置Azure Redis緩存。您的ASP.NET Core應用程序使用RedisDistributedCache實例配置緩存實施。
您能夠ConfigureServices經過請求一個實例IDistributedCache(參見上面的代碼)來配置Redis實現並在您的應用代碼中訪問它。
在示例代碼中,RedisCache當爲服務器配置Staging環境時使用實現。所以該ConfigureStagingServices方法配置RedisCache:
services.AddDistributedRedisCache(options => { options.Configuration = "localhost"; options.InstanceName = "SampleInstance"; });
接着在 Startup.cs 的 Config 方法中配置使用 Session 中間件,全部中間件的配置順序很是重要,必須在 UseSession 調用後才能訪問 Session 。
// 必須在 UseMvc 以前調用 app.UseSession(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); });
在 AddSession 和 UseSession 方法中能夠傳入一個 SessionOptions 參數,經過該參數能夠設置 Session 的 Cookie name, Cookie path 等信息。
配置完成後,就可使用 Session 保存數據了。
具體實現redis實現 http://www.javashuo.com/article/p-kpdswzjy-bq.html
Session 安裝配置好就能夠經過 HttpContext.Session 來保存和讀取數據了。因爲 Session 是基於 IDistributedCache 構建的,所以 Session 只能存儲 byte[] 數據,這樣使用起來很不方便,好在有不少擴展方法能夠用來直接讀取和保存 string、int 等類型數據。
一個 Session 使用的簡單示例:
public IActionResult Index() { HttpContext.Session.SetString("SessionStartedTime", "Session started time:" + DateTime.Now.ToString()); return View(); } public IActionResult About() { ViewData["CurrentTime"] = "Current time:" + DateTime.Now.ToString(); ViewData["SessionStartedTime"] = HttpContext.Session.GetString("SessionStartedTime"); return View(); }
或者設置一個擴展類也能夠直接將實體類序列化成json存儲
public static class SessionExtensions { public static void Set<T>(this ISession session, string key, T value) { session.SetString(key, JsonConvert.SerializeObject(value)); } public static T Get<T>(this ISession session, string key) { var value = session.GetString(key); return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value); } }