在 ASP.NET CORE 中使用 SESSION


Session 是保存用戶和 Web 應用的會話狀態的一種方法,ASP.NET Core 提供了一個用於管理會話狀態的中間件。在本文中我將會簡單介紹一下 ASP.NET Core 中的 Session 的使用方法。

 

安裝配置 Session

nuget 添加引用 Microsoft.AspNetCore.Session 

ession 是基於 IDistributedCache 構建的,所以必須引用一種 IDistributedCache 的實現,ASP.NET Core 提供了多種 IDistributedCache 的實現 (RedisSQL ServerIn-memory) 

In-memory

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

SQL Server

nuget 添加引用 Microsoft.Extensions.Caching.SqlServer

SqlServerCache實現允許分布式緩存使用SQL Server數據庫作為其后備存儲。要創建SQL Server表,您可以使用sql-cache工具,該工具將使用您指定的名稱和模式創建一個表。

要使用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”命令:

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(以及可選地,SchemaNameTableName)通常應該被存儲的源控制(如UserSecrets)以外,因為它們可能包含憑證。

像所有的緩存實現一樣,你的應用程序應該使用一個實例來獲取和設置緩存值IDistributedCache,而不是SqlServerCache該示例SqlServerCacheProduction環境中實現(因此已配置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();

 

Redis

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實現 https://www.cnblogs.com/liuxiaoji/p/9259747.html

使用 Session 存儲數據

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);
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM