本文转自:http://www.cnblogs.com/TomXu/p/4496445.html

当事先的本子中,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节点中补充加如下内容:

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

然后以ConfigureServices中补充加Session的援(并开展配置):

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

末段以Configure方法吃,开启使用Session的模式,如果当上头已布置了了,则好不再传入配置信息,否则要要像面的布置信息相同,传入Session的配置信息,代码如下:

app.UseInMemorySession(configure:s => { s.IdleTimeout = TimeSpan.FromMinutes(30); });
//app.UseSession(o => { o.IdleTimeout = TimeSpan.FromSeconds(30); });
//app.UseInMemorySession(null, null);   //开启内存Session
//app.UseDistributedSession(null, null);//开启分布式Session,也即持久化Session
//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种,代码如下:

public static byte[] Get(this ISessionCollection session, string key);
public static int? GetInt(this ISessionCollection session, string key);
public static string GetString(this ISessionCollection session, string key);
public static void Set(this ISessionCollection session, string key, byte[] value);
public static void SetInt(this ISessionCollection session, string key, int value);
public static void SetString(this ISessionCollection session, string key, string value);

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

Context.Session.SetString("Name", "Mike");
Context.Session.SetInt("Age", 21);

ViewBag.Name = Context.Session.GetString("Name");
ViewBag.Age = Context.Session.GetInt("Age");

于定义类型的Session设置和落

面前我们说了,要保留于定义类型的Session,需要将该类型转换成byte[]数组才行,在本例中,我们本着bool类型的Session数据开展安装及收获的代码,示例如下:

public static class SessionExtensions
{
    public static bool? GetBoolean(this ISessionCollection session, string key)
    {
        var data = session.Get(key);
        if (data == null)
        {
            return null;
        }
        return BitConverter.ToBoolean(data, 0);
    } 

    public static void SetBoolean(this ISessionCollection session, string key, bool value)
    {
        session.Set(key, BitConverter.GetBytes(value));
    }
}

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

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

此外,ISessionCollection接口及还提供了Remove(string
key)和Clear()两独办法分别用于去某个Session值和清空所有的Session值的职能。但同时也得留意,该接口并没有提供之前版本被的Abandon方法效果。

基于Redis的Session管理

以分布式Session,其重大办事就是拿Session保存的地方从原本的外存换到分布式存储上,本节,我们以Redis存储吗例来讲解分布式Session的处理。

先期翻下分布式Session的壮大方法,示例如下,我们得以看到,其Session容器需要是一个支撑IDistributedCache的接口示例。

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

欠接口是缓存Caching的通用接口,也就是说,只要我们落实了缓存接口,就可以那个用于Session的管住。进一步查看该接口发现,该接口中定义的Set方法还欲贯彻一个ICacheContext类型的休养存上下文(以便在调用的下被任何程序开展委托调用),接口定义分别如下:

public interface IDistributedCache
{
    void Connect();
    void Refresh(string key);
    void Remove(string key);
    Stream Set(string key, object state, Action<ICacheContext> create);
    bool TryGetValue(string key, out Stream value);
}

public interface ICacheContext
{
    Stream Data { get; }
    string Key { get; }
    object State { get; }

    void SetAbsoluteExpiration(TimeSpan relative);
    void SetAbsoluteExpiration(DateTimeOffset absolute);
    void SetSlidingExpiration(TimeSpan offset);
}

连着下,我们根据Redis来兑现上述作用,创建RedisCache类,并继承IDistributedCache,引用StackExchange.Redis程序集,然后实现IDistributedCache接口的享有方及性,代码如下:

using Microsoft.Framework.Cache.Distributed;
using Microsoft.Framework.OptionsModel;
using StackExchange.Redis;
using System;
using System.IO;

namespace Microsoft.Framework.Caching.Redis
{
    public class RedisCache : IDistributedCache
    {
        // KEYS[1] = = key
        // ARGV[1] = absolute-expiration - ticks as long (-1 for none)
        // ARGV[2] = sliding-expiration - ticks as long (-1 for none)
        // ARGV[3] = relative-expiration (long, in seconds, -1 for none) - Min(absolute-expiration - Now, sliding-expiration)
        // ARGV[4] = data - byte[]
        // this order should not change LUA script depends on it
        private const string SetScript = (@"
                redis.call('HMSET', KEYS[1], 'absexp', ARGV[1], 'sldexp', ARGV[2], 'data', ARGV[4])
                if ARGV[3] ~= '-1' then
                  redis.call('EXPIRE', KEYS[1], ARGV[3]) 
                end
                return 1");
        private const string AbsoluteExpirationKey = "absexp";
        private const string SlidingExpirationKey = "sldexp";
        private const string DataKey = "data";
        private const long NotPresent = -1;

        private ConnectionMultiplexer _connection;
        private IDatabase _cache;

        private readonly RedisCacheOptions _options;
        private readonly string _instance;

        public RedisCache(IOptions<RedisCacheOptions> optionsAccessor)
        {
            _options = optionsAccessor.Options;
            // This allows partitioning a single backend cache for use with multiple apps/services.
            _instance = _options.InstanceName ?? string.Empty;
        }

        public void Connect()
        {
            if (_connection == null)
            {
                _connection = ConnectionMultiplexer.Connect(_options.Configuration);
                _cache = _connection.GetDatabase();
            }
        }

        public Stream Set(string key, object state, Action<ICacheContext> create)
        {
            Connect();

            var context = new CacheContext(key) { State = state };
            create(context);
            var value = context.GetBytes();
            var result = _cache.ScriptEvaluate(SetScript, new RedisKey[] { _instance + key },
                new RedisValue[]
                {
                    context.AbsoluteExpiration?.Ticks ?? NotPresent,
                    context.SlidingExpiration?.Ticks ?? NotPresent,
                    context.GetExpirationInSeconds() ?? NotPresent,
                    value
                });
            // TODO: Error handling
            return new MemoryStream(value, writable: false);
        }

        public bool TryGetValue(string key, out Stream value)
        {
            value = GetAndRefresh(key, getData: true);
            return value != null;
        }

        public void Refresh(string key)
        {
            var ignored = GetAndRefresh(key, getData: false);
        }

        private Stream GetAndRefresh(string key, bool getData)
        {
            Connect();

            // This also resets the LRU status as desired.
            // TODO: Can this be done in one operation on the server side? Probably, the trick would just be the DateTimeOffset math.
            RedisValue[] results;
            if (getData)
            {
                results = _cache.HashMemberGet(_instance + key, AbsoluteExpirationKey, SlidingExpirationKey, DataKey);
            }
            else
            {
                results = _cache.HashMemberGet(_instance + key, AbsoluteExpirationKey, SlidingExpirationKey);
            }
            // TODO: Error handling
            if (results.Length >= 2)
            {
                // Note we always get back two results, even if they are all null.
                // These operations will no-op in the null scenario.
                DateTimeOffset? absExpr;
                TimeSpan? sldExpr;
                MapMetadata(results, out absExpr, out sldExpr);
                Refresh(key, absExpr, sldExpr);
            }
            if (results.Length >= 3 && results[2].HasValue)
            {
                return new MemoryStream(results[2], writable: false);
            }
            return null;
        }

        private void MapMetadata(RedisValue[] results, out DateTimeOffset? absoluteExpiration, out TimeSpan? slidingExpiration)
        {
            absoluteExpiration = null;
            slidingExpiration = null;
            var absoluteExpirationTicks = (long?)results[0];
            if (absoluteExpirationTicks.HasValue && absoluteExpirationTicks.Value != NotPresent)
            {
                absoluteExpiration = new DateTimeOffset(absoluteExpirationTicks.Value, TimeSpan.Zero);
            }
            var slidingExpirationTicks = (long?)results[1];
            if (slidingExpirationTicks.HasValue && slidingExpirationTicks.Value != NotPresent)
            {
                slidingExpiration = new TimeSpan(slidingExpirationTicks.Value);
            }
        }

        private void Refresh(string key, DateTimeOffset? absExpr, TimeSpan? sldExpr)
        {
            // Note Refresh has no effect if there is just an absolute expiration (or neither).
            TimeSpan? expr = null;
            if (sldExpr.HasValue)
            {
                if (absExpr.HasValue)
                {
                    var relExpr = absExpr.Value - DateTimeOffset.Now;
                    expr = relExpr <= sldExpr.Value ? relExpr : sldExpr;
                }
                else
                {
                    expr = sldExpr;
                }
                _cache.KeyExpire(_instance + key, expr);
                // TODO: Error handling
            }
        }

        public void Remove(string key)
        {
            Connect();

            _cache.KeyDelete(_instance + key);
            // TODO: Error handling
        }
    }
}

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

public class RedisCacheOptions : IOptions<RedisCacheOptions>
{
    public string Configuration { get; set; }

    public string InstanceName { get; set; }

    RedisCacheOptions IOptions<RedisCacheOptions>.Options
    {
        get { return this; }
    }

    RedisCacheOptions IOptions<RedisCacheOptions>.GetNamedOptions(string name)
    {
        return this;
    }
}

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

using Microsoft.Framework.Cache.Distributed;
using System;
using System.IO;

namespace Microsoft.Framework.Caching.Redis
{
    internal class CacheContext : ICacheContext
    {
        private readonly MemoryStream _data = new MemoryStream();

        internal CacheContext(string key)
        {
            Key = key;
            CreationTime = DateTimeOffset.UtcNow;
        }

        /// <summary>
        /// The key identifying this entry.
        /// </summary>
        public string Key { get; internal set; }

        /// <summary>
        /// The state passed into Set. This can be used to avoid closures.
        /// </summary>
        public object State { get; internal set; }

        public Stream Data { get { return _data; } }

        internal DateTimeOffset CreationTime { get; set; } // 可以让委托设置创建时间

        internal DateTimeOffset? AbsoluteExpiration { get; private set; }

        internal TimeSpan? SlidingExpiration { get; private set; }

        public void SetAbsoluteExpiration(TimeSpan relative) // 可以让委托设置相对过期时间
        {
            if (relative <= TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException("relative", relative, "The relative expiration value must be positive.");
            }
            AbsoluteExpiration = CreationTime + relative;
        }

        public void SetAbsoluteExpiration(DateTimeOffset absolute) // 可以让委托设置绝对过期时间
        {
            if (absolute <= CreationTime)
            {
                throw new ArgumentOutOfRangeException("absolute", absolute, "The absolute expiration value must be in the future.");
            }
            AbsoluteExpiration = absolute.ToUniversalTime();
        }

        public void SetSlidingExpiration(TimeSpan offset) // 可以让委托设置offset过期时间
        {
            if (offset <= TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException("offset", offset, "The sliding expiration value must be positive.");
            }
            SlidingExpiration = offset;
        }

        internal long? GetExpirationInSeconds()
        {
            if (AbsoluteExpiration.HasValue && SlidingExpiration.HasValue)
            {
                return (long)Math.Min((AbsoluteExpiration.Value - CreationTime).TotalSeconds, SlidingExpiration.Value.TotalSeconds);
            }
            else if (AbsoluteExpiration.HasValue)
            {
                return (long)(AbsoluteExpiration.Value - CreationTime).TotalSeconds;
            }
            else if (SlidingExpiration.HasValue)
            {
                return (long)SlidingExpiration.Value.TotalSeconds;
            }
            return null;
        }

        internal byte[] GetBytes()
        {
            return _data.ToArray();
        }
    }
}

最终一步定义,RedisCache遭逢需要之依据key键获取缓存值的神速方法,代码如下:

using StackExchange.Redis;
using System;

namespace Microsoft.Framework.Caching.Redis
{
    internal static class RedisExtensions
    {
        private const string HmGetScript = (@"return redis.call('HMGET', KEYS[1], unpack(ARGV))");

        internal static RedisValue[] HashMemberGet(this IDatabase cache, string key, params string[] members)
        {
            var redisMembers = new RedisValue[members.Length];
            for (int i = 0; i < members.Length; i++)
            {
                redisMembers[i] = (RedisValue)members[i];
            }
            var result = cache.ScriptEvaluate(HmGetScript, new RedisKey[] { key }, redisMembers);
            // TODO: Error checking?
            return (RedisValue[])result;
        }
    }
}

从那之后,所有的工作就做到了,将该缓存实现登记为Session的provider的代码方法如下:

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

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

关于Caching

默认情况下,本地缓存使用的凡IMemoryCache接口的言传身教,可以由此获得该接口的演示来针对当地缓存进行操作,示例代码如下:

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

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

public static class CachingServicesExtensions
{
    public static IServiceCollection AddCaching(this IServiceCollection collection)
    {
        collection.AddOptions();
        return collection.AddTransient<IDistributedCache, LocalCache>()
            .AddSingleton<IMemoryCache, MemoryCache>();
    }
}

因而,要利用新的分布式Caching实现,我们用登记自己之落实,代码如下:

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

主导的用办法如下:

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

协跟推介

本文就联合到目录索引:解读ASP.NET 5 &
MVC6系列

 

相关文章

网站地图xml地图