在 ASP.NET CORE 中使用 SESSION

Session 是保存用户和 Web 应用的会话状态的一种方法,ASP.NET Core 提供了一个用于管理会话状态的中间件。在本文中我将会简单介绍一下 ASP.NET Core 中的 Session 的使用方法。html

 

安装配置 Session

nuget 添加引用 Microsoft.AspNetCore.Session redis

ession 是基于 IDistributedCache 构建的,因此必须引用一种 IDistributedCache 的实现,ASP.NET Core 提供了多种 IDistributedCache 的实现 (RedisSQL ServerIn-memory) sql

In-memory

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

SQL Server

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(以及可选地,SchemaNameTableName)一般应该被存储的源控制(如UserSecrets)之外,由于它们可能包含凭证。app

像全部的缓存实现同样,你的应用程序应该使用一个实例来获取和设置缓存值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实现 http://www.javashuo.com/article/p-kpdswzjy-bq.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);
        }
    }
相关文章
相关标签/搜索