在之前的版本中,Session存在于System.Web中,新版ASP.NET 5中由于不在依赖于System.Web.dll库了,所以相应的,Session也就成了ASP.NET 5中一个可配置的模块(middleware)了。

配置启用Session

ASP.NET 5中的Session模块存在于Microsoft.AspNet.Session类库中,要启用Session,首先需要在project.json中的dependencies节点中添加如下内容:

  1. "Microsoft.AspNet.Session": "1.0.0-beta3"

然后在ConfigureServices中添加Session的引用(并进行配置):

  1. services.AddCaching(); // 这两个必须同时添加,因为Session依赖于Caching
  2. services.AddSession();
  3. //services.ConfigureSession(null); 可以在这里配置,也可以再后面进行配置

最后在Configure方法中,开启使用Session的模式,如果在上面已经配置过了,则可以不再传入配置信息,否则还是要像上面的配置信息一样,传入Session的配置信息,代码如下:

  1. app.UseInMemorySession(configure:s => { s.IdleTimeout = TimeSpan.FromMinutes(30); });
  2. //app.UseSession(o => { o.IdleTimeout = TimeSpan.FromSeconds(30); });
  3. //app.UseInMemorySession(null, null); //开启内存Session
  4. //app.UseDistributedSession(null, null);//开启分布式Session,也即持久化Session
  5. //app.UseDistributedSession(new RedisCache(new RedisCacheOptions() { Configuration = "localhost" }));

对于UseInMemorySession方法,接收2个可选参数,分别是:IMemoryCache可用于修改Session数据的默认保存地址;Action<SessionOptions>委托则可以让你修改默认选项,比如Session cookie的路径、默认的过期时间等。本例中,我们修改默认过期时间为30分钟。

注意:该方法必须在app.UseMvc之前调用,否则在Mvc里获取不到Session,而且会出错。

获取和设置Session

获取和设置Session对象,一般是在Controller的action里通过this.Context.Session来获取的,其获取的是一个基于接口ISessionCollection的实例。该接口可以通过索引、Set、TryGetValue等方法进行Session值的获取和设置,但我们发现在获取和设置Session的时候,我们只能使用byte[]类型,而不能像之前版本的Session一样可以设置任意类型的数据。原因是因为,新版本的Session要支持在远程服务器上存储,就需要支持序列化,所以才强制要求保存为byte[]类型。所以我们在保存Session的时候,需要将其转换为byte[]才能进行保存,并且获取以后要再次将byte[]转换为自己的原有的类型才行。这种形式太麻烦了,好在微软在Microsoft.AspNet.Http命名空间(所属Microsoft.AspNet.Http.Extensions.dll中)下,为我们添加了几个扩展方法,分别用于设置和保存byte[]类型、int类型、以及string类型,代码如下:

  1. public static byte[] Get(this ISessionCollection session, string key);
  2. public static int? GetInt(this ISessionCollection session, string key);
  3. public static string GetString(this ISessionCollection session, string key);
  4. public static void Set(this ISessionCollection session, string key, byte[] value);
  5. public static void SetInt(this ISessionCollection session, string key, int value);
  6. public static void SetString(this ISessionCollection session, string key, string value);

所以,在Controller里引用Microsoft.AspNet.Http命名空间以后,我们就可以通过如下代码进行Session的设置和获取了:

  1. Context.Session.SetString("Name", "Mike");
  2. Context.Session.SetInt("Age", 21);
  3. ViewBag.Name = Context.Session.GetString("Name");
  4. ViewBag.Age = Context.Session.GetInt("Age");

自定义类型的Session设置和获取

前面我们说了,要保存自定义类型的Session,需要将其类型转换成byte[]数组才行,在本例中,我们对bool类型的Session数据进行设置和获取的代码,示例如下:

  1. public static class SessionExtensions
  2. {
  3. public static bool? GetBoolean(this ISessionCollection session, string key)
  4. {
  5. var data = session.Get(key);
  6. if (data == null)
  7. {
  8. return null;
  9. }
  10. return BitConverter.ToBoolean(data, 0);
  11. }
  12. public static void SetBoolean(this ISessionCollection session, string key, bool value)
  13. {
  14. session.Set(key, BitConverter.GetBytes(value));
  15. }
  16. }

定义bool类型的扩展方法以后,我们就可以像SetInt/GetInt那样进行使用了,示例如下:

  1. Context.Session.SetBoolean("Liar", true);
  2. ViewBag.Liar = Context.Session.GetBoolean("Liar");

另外,ISessionCollection接口上还提供了Remove(string key)和Clear()两个方法分别用于删除某个Session值和清空所有的Session值的功能。但同时也需要注意,该接口并没提供之前版本中的Abandon方法功能。

基于Redis的Session管理

使用分布式Session,其主要工作就是将Session保存的地方从原来的内存换到分布式存储上,本节,我们以Redis存储为例来讲解分布式Session的处理。

先查看使用分布式Session的扩展方法,示例如下,我们可以看到,其Session容器需要是一个支持IDistributedCache的接口示例。

  1. public static IApplicationBuilder UseDistributedSession([NotNullAttribute]this IApplicationBuilder app, IDistributedCache cache, Action<SessionOptions> configure = null);

该接口是缓存Caching的通用接口,也就是说,只要我们实现了缓存接口,就可以将其用于Session的管理。进一步查看该接口发现,该接口中定义的Set方法还需要实现一个ICacheContext类型的缓存上下文(以便在调用的时候让其它程序进行委托调用),接口定义分别如下:

  1. public interface IDistributedCache
  2. {
  3. void Connect();
  4. void Refresh(string key);
  5. void Remove(string key);
  6. Stream Set(string key, object state, Action<ICacheContext> create);
  7. bool TryGetValue(string key, out Stream value);
  8. }
  9. public interface ICacheContext
  10. {
  11. Stream Data { get; }
  12. string Key { get; }
  13. object State { get; }
  14. void SetAbsoluteExpiration(TimeSpan relative);
  15. void SetAbsoluteExpiration(DateTimeOffset absolute);
  16. void SetSlidingExpiration(TimeSpan offset);
  17. }

接下来,我们基于Redis来实现上述功能,创建RedisCache类,并继承IDistributedCache,引用StackExchange.Redis程序集,然后实现IDistributedCache接口的所有方法和属性,代码如下:

  1. using Microsoft.Framework.Cache.Distributed;
  2. using Microsoft.Framework.OptionsModel;
  3. using StackExchange.Redis;
  4. using System;
  5. using System.IO;
  6. namespace Microsoft.Framework.Caching.Redis
  7. {
  8. public class RedisCache : IDistributedCache
  9. {
  10. // KEYS[1] = = key
  11. // ARGV[1] = absolute-expiration - ticks as long (-1 for none)
  12. // ARGV[2] = sliding-expiration - ticks as long (-1 for none)
  13. // ARGV[3] = relative-expiration (long, in seconds, -1 for none) - Min(absolute-expiration - Now, sliding-expiration)
  14. // ARGV[4] = data - byte[]
  15. // this order should not change LUA script depends on it
  16. private const string SetScript = (@"
  17. redis.call('HMSET', KEYS[1], 'absexp', ARGV[1], 'sldexp', ARGV[2], 'data', ARGV[4])
  18. if ARGV[3] ~= '-1' then
  19. redis.call('EXPIRE', KEYS[1], ARGV[3])
  20. end
  21. return 1");
  22. private const string AbsoluteExpirationKey = "absexp";
  23. private const string SlidingExpirationKey = "sldexp";
  24. private const string DataKey = "data";
  25. private const long NotPresent = -1;
  26. private ConnectionMultiplexer _connection;
  27. private IDatabase _cache;
  28. private readonly RedisCacheOptions _options;
  29. private readonly string _instance;
  30. public RedisCache(IOptions<RedisCacheOptions> optionsAccessor)
  31. {
  32. _options = optionsAccessor.Options;
  33. // This allows partitioning a single backend cache for use with multiple apps/services.
  34. _instance = _options.InstanceName ?? string.Empty;
  35. }
  36. public void Connect()
  37. {
  38. if (_connection == null)
  39. {
  40. _connection = ConnectionMultiplexer.Connect(_options.Configuration);
  41. _cache = _connection.GetDatabase();
  42. }
  43. }
  44. public Stream Set(string key, object state, Action<ICacheContext> create)
  45. {
  46. Connect();
  47. var context = new CacheContext(key) { State = state };
  48. create(context);
  49. var value = context.GetBytes();
  50. var result = _cache.ScriptEvaluate(SetScript, new RedisKey[] { _instance + key },
  51. new RedisValue[]
  52. {
  53. context.AbsoluteExpiration?.Ticks ?? NotPresent,
  54. context.SlidingExpiration?.Ticks ?? NotPresent,
  55. context.GetExpirationInSeconds() ?? NotPresent,
  56. value
  57. });
  58. // TODO: Error handling
  59. return new MemoryStream(value, writable: false);
  60. }
  61. public bool TryGetValue(string key, out Stream value)
  62. {
  63. value = GetAndRefresh(key, getData: true);
  64. return value != null;
  65. }
  66. public void Refresh(string key)
  67. {
  68. var ignored = GetAndRefresh(key, getData: false);
  69. }
  70. private Stream GetAndRefresh(string key, bool getData)
  71. {
  72. Connect();
  73. // This also resets the LRU status as desired.
  74. // TODO: Can this be done in one operation on the server side? Probably, the trick would just be the DateTimeOffset math.
  75. RedisValue[] results;
  76. if (getData)
  77. {
  78. results = _cache.HashMemberGet(_instance + key, AbsoluteExpirationKey, SlidingExpirationKey, DataKey);
  79. }
  80. else
  81. {
  82. results = _cache.HashMemberGet(_instance + key, AbsoluteExpirationKey, SlidingExpirationKey);
  83. }
  84. // TODO: Error handling
  85. if (results.Length >= 2)
  86. {
  87. // Note we always get back two results, even if they are all null.
  88. // These operations will no-op in the null scenario.
  89. DateTimeOffset? absExpr;
  90. TimeSpan? sldExpr;
  91. MapMetadata(results, out absExpr, out sldExpr);
  92. Refresh(key, absExpr, sldExpr);
  93. }
  94. if (results.Length >= 3 && results[2].HasValue)
  95. {
  96. return new MemoryStream(results[2], writable: false);
  97. }
  98. return null;
  99. }
  100. private void MapMetadata(RedisValue[] results, out DateTimeOffset? absoluteExpiration, out TimeSpan? slidingExpiration)
  101. {
  102. absoluteExpiration = null;
  103. slidingExpiration = null;
  104. var absoluteExpirationTicks = (long?)results[0];
  105. if (absoluteExpirationTicks.HasValue && absoluteExpirationTicks.Value != NotPresent)
  106. {
  107. absoluteExpiration = new DateTimeOffset(absoluteExpirationTicks.Value, TimeSpan.Zero);
  108. }
  109. var slidingExpirationTicks = (long?)results[1];
  110. if (slidingExpirationTicks.HasValue && slidingExpirationTicks.Value != NotPresent)
  111. {
  112. slidingExpiration = new TimeSpan(slidingExpirationTicks.Value);
  113. }
  114. }
  115. private void Refresh(string key, DateTimeOffset? absExpr, TimeSpan? sldExpr)
  116. {
  117. // Note Refresh has no effect if there is just an absolute expiration (or neither).
  118. TimeSpan? expr = null;
  119. if (sldExpr.HasValue)
  120. {
  121. if (absExpr.HasValue)
  122. {
  123. var relExpr = absExpr.Value - DateTimeOffset.Now;
  124. expr = relExpr <= sldExpr.Value ? relExpr : sldExpr;
  125. }
  126. else
  127. {
  128. expr = sldExpr;
  129. }
  130. _cache.KeyExpire(_instance + key, expr);
  131. // TODO: Error handling
  132. }
  133. }
  134. public void Remove(string key)
  135. {
  136. Connect();
  137. _cache.KeyDelete(_instance + key);
  138. // TODO: Error handling
  139. }
  140. }
  141. }

在上述代码中,我们使用了自定义类RedisCacheOptions作为Redis的配置信息类,为了实现基于POCO的配置定义,我们还继承了IOptions接口,该类的定义如下:

  1. public class RedisCacheOptions : IOptions<RedisCacheOptions>
  2. {
  3. public string Configuration { get; set; }
  4. public string InstanceName { get; set; }
  5. RedisCacheOptions IOptions<RedisCacheOptions>.Options
  6. {
  7. get { return this; }
  8. }
  9. RedisCacheOptions IOptions<RedisCacheOptions>.GetNamedOptions(string name)
  10. {
  11. return this;
  12. }
  13. }

第三部,定义委托调用时使用的缓存上下文类CacheContext,具体代码如下:

  1. using Microsoft.Framework.Cache.Distributed;
  2. using System;
  3. using System.IO;
  4. namespace Microsoft.Framework.Caching.Redis
  5. {
  6. internal class CacheContext : ICacheContext
  7. {
  8. private readonly MemoryStream _data = new MemoryStream();
  9. internal CacheContext(string key)
  10. {
  11. Key = key;
  12. CreationTime = DateTimeOffset.UtcNow;
  13. }
  14. /// <summary>
  15. /// The key identifying this entry.
  16. /// </summary>
  17. public string Key { get; internal set; }
  18. /// <summary>
  19. /// The state passed into Set. This can be used to avoid closures.
  20. /// </summary>
  21. public object State { get; internal set; }
  22. public Stream Data { get { return _data; } }
  23. internal DateTimeOffset CreationTime { get; set; } // 可以让委托设置创建时间
  24. internal DateTimeOffset? AbsoluteExpiration { get; private set; }
  25. internal TimeSpan? SlidingExpiration { get; private set; }
  26. public void SetAbsoluteExpiration(TimeSpan relative) // 可以让委托设置相对过期时间
  27. {
  28. if (relative <= TimeSpan.Zero)
  29. {
  30. throw new ArgumentOutOfRangeException("relative", relative, "The relative expiration value must be positive.");
  31. }
  32. AbsoluteExpiration = CreationTime + relative;
  33. }
  34. public void SetAbsoluteExpiration(DateTimeOffset absolute) // 可以让委托设置绝对过期时间
  35. {
  36. if (absolute <= CreationTime)
  37. {
  38. throw new ArgumentOutOfRangeException("absolute", absolute, "The absolute expiration value must be in the future.");
  39. }
  40. AbsoluteExpiration = absolute.ToUniversalTime();
  41. }
  42. public void SetSlidingExpiration(TimeSpan offset) // 可以让委托设置offset过期时间
  43. {
  44. if (offset <= TimeSpan.Zero)
  45. {
  46. throw new ArgumentOutOfRangeException("offset", offset, "The sliding expiration value must be positive.");
  47. }
  48. SlidingExpiration = offset;
  49. }
  50. internal long? GetExpirationInSeconds()
  51. {
  52. if (AbsoluteExpiration.HasValue && SlidingExpiration.HasValue)
  53. {
  54. return (long)Math.Min((AbsoluteExpiration.Value - CreationTime).TotalSeconds, SlidingExpiration.Value.TotalSeconds);
  55. }
  56. else if (AbsoluteExpiration.HasValue)
  57. {
  58. return (long)(AbsoluteExpiration.Value - CreationTime).TotalSeconds;
  59. }
  60. else if (SlidingExpiration.HasValue)
  61. {
  62. return (long)SlidingExpiration.Value.TotalSeconds;
  63. }
  64. return null;
  65. }
  66. internal byte[] GetBytes()
  67. {
  68. return _data.ToArray();
  69. }
  70. }
  71. }

最后一步定义,RedisCache中需要的根据key键获取缓存值的快捷方法,代码如下:

  1. using StackExchange.Redis;
  2. using System;
  3. namespace Microsoft.Framework.Caching.Redis
  4. {
  5. internal static class RedisExtensions
  6. {
  7. private const string HmGetScript = (@"return redis.call('HMGET', KEYS[1], unpack(ARGV))");
  8. internal static RedisValue[] HashMemberGet(this IDatabase cache, string key, params string[] members)
  9. {
  10. var redisMembers = new RedisValue[members.Length];
  11. for (int i = 0; i < members.Length; i++)
  12. {
  13. redisMembers[i] = (RedisValue)members[i];
  14. }
  15. var result = cache.ScriptEvaluate(HmGetScript, new RedisKey[] { key }, redisMembers);
  16. // TODO: Error checking?
  17. return (RedisValue[])result;
  18. }
  19. }
  20. }

至此,所有的工作就完成了,将该缓存实现注册为Session的provider的代码方法如下:

  1. app.UseDistributedSession(new RedisCache(new RedisCacheOptions()
  2. {
  3. Configuration = "此处填写 redis的地址",
  4. InstanceName = "此处填写自定义实例名"
  5. }), options =>
  6. {
  7. options.CookieHttpOnly = true;
  8. });

参考:http://www.mikesdotnetting.com/article/270/sessions-in-asp-net-5

关于Caching

默认情况下,本地缓存使用的是IMemoryCache接口的示例,可以通过获取该接口的示例来对本地缓存进行操作,示例代码如下:

  1. var cache = app.ApplicationServices.GetRequiredService<IMemoryCache>();
  2. var obj1 = cache.Get("key1");
  3. bool obj2 = cache.Get<bool>("key2");

对于,分布式缓存,由于AddCaching,默认将IMemoryCache实例作为分布式缓存的provider了,代码如下:

  1. public static class CachingServicesExtensions
  2. {
  3. public static IServiceCollection AddCaching(this IServiceCollection collection)
  4. {
  5. collection.AddOptions();
  6. return collection.AddTransient<IDistributedCache, LocalCache>()
  7. .AddSingleton<IMemoryCache, MemoryCache>();
  8. }
  9. }

所以,要使用新的分布式Caching实现,我们需要注册自己的实现,代码如下:

  1. services.AddTransient<IDistributedCache, RedisCache>();
  2. services.Configure<RedisCacheOptions>(opt =>
  3. {
  4. opt.Configuration = "此处填写 redis的地址";
  5. opt.InstanceName = "此处填写自定义实例名";
  6. });

基本的使用方法如下:

  1. var cache = app.ApplicationServices.GetRequiredService<IDistributedCache>();
  2. cache.Connect();
  3. var obj1 = cache.Get("key1"); //该对象是流,需要将其转换为强类型,或自己再编写扩展方法
  4. var bytes = obj1.ReadAllBytes();

同步与推荐

本文已同步至目录索引:解读ASP.NET 5 & MVC6系列

解读ASP.NET 5 & MVC6系列(8):Session与Caching的更多相关文章

  1. [转]解读ASP.NET 5 & MVC6系列(8):Session与Caching

    本文转自:http://www.cnblogs.com/TomXu/p/4496445.html 在之前的版本中,Session存在于System.Web中,新版ASP.NET 5中由于不在依赖于Sy ...

  2. 解读ASP.NET 5 & MVC6系列

    本系列的大部分内容来自于微软源码的阅读和网络,大部分测试代码都是基于VS RC版本进行测试的. 解读ASP.NET 5 & MVC6系列(1):ASP.NET 5简介 解读ASP.NET 5 ...

  3. 解读ASP.NET 5 & MVC6系列(1):ASP.NET 5简介

    ASP.NET 5简介 ASP.NET 5是一个跨时代的改写,所有的功能和模块都进行了独立拆分,做到了彻底解耦.为了这些改写,微软也是蛮 拼的,几乎把.NET Framwrok全部改写了一遍,形成了一 ...

  4. 解读ASP.NET 5 & MVC6 ---- 系列文章

    本系列的大部分内容来自于微软源码的阅读和网络,大部分测试代码都是基于VS RC版本进行测试的. 解读ASP.NET 5 & MVC6系列(1):ASP.NET 5简介 解读ASP.NET 5 ...

  5. [转帖]2016年的文章: 解读ASP.NET 5 & MVC6系列教程(1):ASP.NET 5简介

    解读ASP.NET 5 & MVC6系列教程(1):ASP.NET 5简介 更新时间:2016年06月23日 11:38:00   作者:汤姆大叔    我要评论 https://www.jb ...

  6. 解读ASP.NET 5 & MVC6系列(17):MVC中的其他新特性

    (GlobalImport全局导入功能) 默认新建立的MVC程序中,在Views目录下,新增加了一个_GlobalImport.cshtml文件和_ViewStart.cshtml平级,该文件的功能类 ...

  7. 解读ASP.NET 5 & MVC6系列(16):自定义View视图文件查找逻辑

    之前MVC5和之前的版本中,我们要想对View文件的路径进行控制的话,则必须要对IViewEngine接口的FindPartialView或FindView方法进行重写,所有的视图引擎都继承于该IVi ...

  8. 解读ASP.NET 5 & MVC6系列(15):MvcOptions配置

    程序模型处理 IApplicationModelConvention 在MvcOptions的实例对象上,有一个ApplicationModelConventions属性(类型是:List<IA ...

  9. 解读ASP.NET 5 & MVC6系列(14):View Component

    在之前的MVC中,我们经常需要类似一种小部件的功能,通常我们都是使用Partial View来实现,因为MVC中没有类似Web Forms中的WebControl的功能.但在MVC6中,这一功能得到了 ...

随机推荐

  1. Vertica DBD 分析优化设计

    DBD = Database Designer,是Vertica数据库优化中最主要的原生工具. 首先运行admintools工具,按下面步骤依次执行: 1.选择"6 Configuratio ...

  2. 响应式图片菜单式轮播,兼容手机,平板,PC

    昨天在给自己用bootstrap写一个响应式主业模版时想用一个图片轮播js,看到了bootstrap里面的unslider.js,只有1.7k,很小,很兴奋,但使用到最后发现不兼容手机,当分辨率变化的 ...

  3. CLR和.Net对象生存周期

    标签:GC .Net C# CLR 前言 1. 基础概念明晰 * 1.1 公告语言运行时 * 1.2 托管模块 * 1.3 对象和类型 * 1.4 垃圾回收器 2. 垃圾回收模型 * 2.1 为什么需 ...

  4. Devexpress Ribbon Add Logo

    一直在网上找类似的效果.在Devpexress控件里面的这个是一个Demo的.没法查看源代码.也不知道怎么写的.所以就在网上搜索了半天的. 终于找到类似的解决办法. 可以使用重绘制的办法的来解决. [ ...

  5. asp.net创建事务的方法

    1.建立List用于存放多条语句 /// <summary> /// 保存表单 /// </summary> /// <param name="context& ...

  6. iOS学习笔记——滚动视图(scrollView)

    滚动视图:在根视图中添加UIScrollViewDelegate协议,声明一些对象属性 @interface BoViewController : UIViewController<UIScro ...

  7. JAVA 入门第二章 (面对对象)

    本渣渣鸽了一个月终于有时间更新.因为有c++基础,学起来这章还是比较简单的,本章我觉得是程序猿质变课程,理解面向对象的思想,掌握面向对象的基本原则以及 Java 面向对象编程基本实现原理,熟练使用封装 ...

  8. JavaWeb之XML详解

    XML语言 什么是XML? XML是指可扩展标记语言(eXtensible Markup Language),它是一种标记语言,很类似HTML.它被设计的宗旨是传输数据,而非显示数据. XML标签没有 ...

  9. angularjs 弹出框 $modal

    angularjs 弹出框 $modal 标签: angularjs 2015-11-04 09:50 8664人阅读 评论(1) 收藏 举报  分类: Angularjs(3)  $modal只有一 ...

  10. centos 域名硬解析(linux)

    centos做硬解析跟Windows一样修改一个文件. 具体文件为:/etc/hosts.修改命令: vi /etc/hosts 格式个Windows也一样的.