"Microsoft.AspNet.Session": "1.0.0-beta3"
services.AddCaching(); // 这两个必须同时添加,因为Session依赖于Caching services.AddSession(); //services.ConfigureSession(null); 可以在这里配置,也可以再后面进行配置
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" }));
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);
Context.Session.SetString("Name", "Mike");
Context.Session.SetInt("Age", 21);
ViewBag.Name = Context.Session.GetString("Name");
ViewBag.Age = Context.Session.GetInt("Age");
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));
}
}
Context.Session.SetBoolean("Liar", true);
ViewBag.Liar = Context.Session.GetBoolean("Liar");
public static IApplicationBuilder UseDistributedSession([NotNullAttribute]this IApplicationBuilder app, IDistributedCache cache, Action<SessionOptions> configure = null);
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);
}
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
}
}
}
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;
}
}
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();
}
}
}
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;
}
}
}
app.UseDistributedSession(new RedisCache(new RedisCacheOptions()
{
Configuration = "此处填写 redis的地址",
InstanceName = "此处填写自定义实例名"
}), options =>
{
options.CookieHttpOnly = true;
});
var cache = app.ApplicationServices.GetRequiredService<IMemoryCache>();
var obj1 = cache.Get("key1");
bool obj2 = cache.Get<bool>("key2");
public static class CachingServicesExtensions
{
public static IServiceCollection AddCaching(this IServiceCollection collection)
{
collection.AddOptions();
return collection.AddTransient<IDistributedCache, LocalCache>()
.AddSingleton<IMemoryCache, MemoryCache>();
}
}
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();
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有