实现代码:

//声名一个数据集合
var listString = new List<string>() { "a", "b", "c" };
//缓存key
string key = "cokey"; //获取实例
var cookiesManager = CookiesManager<List<string>>.GetInstance(); //插入缓存
cookiesManager.Add(key, listString, cookiesManager.Minutes * );//过期30分钟
//add有其它重载 上面是最基本的 //获取
List<string> cookiesList = cookiesManager[key]; //其它方法
cookiesManager.ContainsKey(key); cookiesManager.Remove(key);//删除 cookiesManager.RemoveAll(c => c.Contains("sales_"));//删除key包含sales_的cookies cookiesManager.GetAllKey();//获取所有key

封装类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web; namespace SyntacticSugar
{ /// <summary>
/// ** 描述:cookies操作类
/// ** 创始时间:2015-6-9
/// ** 修改时间:-
/// ** 作者:sunkaixuan
/// ** 使用说明:
/// </summary>
/// <typeparam name="V">值</typeparam>
public class CookiesManager<V> : IHttpStorageObject<V>
{ #region 全局变量
private static CookiesManager<V> _instance = null;
private static readonly object _instanceLock = new object();
#endregion /// <summary>
/// 获取实例 (单例模式)
/// </summary>
/// <returns></returns>
public static CookiesManager<V> GetInstance()
{
if (_instance == null)
lock (_instanceLock)
if (_instance == null)
_instance = new CookiesManager<V>();
return _instance;
} /// <summary>
/// 添加cookies ,注意value最大4K (默认1天)
/// </summary>
/// <param name="key">key</param>
/// <param name="value">value</param>
public override void Add(string key, V value)
{
Add(key, value, Day);
}
/// <summary>
/// 添加cookies ,注意value最大4K
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="cookiesDurationInSeconds">有效时间单位秒</param>
public void Add(string key, V value, int cookiesDurationInSeconds)
{
HttpResponse response = HttpContext.Current.Response;
if (response != null)
{
HttpCookie cookie = response.Cookies[key];
if (cookie != null)
{
if (typeof(V) == typeof(string))
{
string setValue = value.ToString();
Add(key, cookiesDurationInSeconds, cookie, setValue, response);
}
else
{
System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
string setValue = jss.Serialize(value);
Add(key, cookiesDurationInSeconds, cookie, setValue, response); }
}
}
} private void Add(string key, int cookiesDurationInSeconds, HttpCookie cookie, string setValue, HttpResponse response)
{
if (!string.IsNullOrEmpty(key) && cookie.HasKeys)
cookie.Values.Set(key, setValue);
else
if (!string.IsNullOrEmpty(setValue))
cookie.Value = setValue;
if (cookiesDurationInSeconds > )
cookie.Expires = DateTime.Now.AddSeconds(cookiesDurationInSeconds);
response.SetCookie(cookie);
} public override bool ContainsKey(string key)
{
return Get(key) != null;
} public override V Get(string key)
{
string value = string.Empty;
if (context.Request.Cookies[key] != null)
value = context.Request.Cookies[key].Value;
if (typeof(V) == typeof(string))
{
return (V)Convert.ChangeType(value, typeof(V));
}
else
{
System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
return jss.Deserialize<V>(value);
}
} public override IEnumerable<string> GetAllKey()
{
var allKeyList = context.Request.Cookies.AllKeys.ToList();
foreach (var key in allKeyList)
{
yield return key;
}
} public override void Remove(string key)
{
HttpRequest request = HttpContext.Current.Request;
if (request != null)
{
HttpCookie cookie = request.Cookies[key];
cookie.Expires = DateTime.Now.AddDays(-);
if (cookie != null)
{
if (!string.IsNullOrEmpty(key) && cookie.HasKeys)
cookie.Values.Remove(key);
else
request.Cookies.Remove(key);
}
}
} public override void RemoveAll()
{
foreach (var key in GetAllKey())
{
Remove(key);
}
} public override void RemoveAll(Func<string, bool> removeExpression)
{
var removeList = GetAllKey().Where(removeExpression).ToList();
foreach (var key in removeList)
{
Remove(key);
}
} public override V this[string key]
{
get { return Get(key); }
}
}
}
using System;
namespace SyntacticSugar
{
public abstract class IHttpStorageObject<V>
{ public int Minutes = ;
public int Hour = * ;
public int Day = * * ;
public System.Web.HttpContext context = System.Web.HttpContext.Current;
public abstract void Add(string key, V value);
public abstract bool ContainsKey(string key);
public abstract V Get(string key);
public abstract global::System.Collections.Generic.IEnumerable<string> GetAllKey();
public abstract void Remove(string key);
public abstract void RemoveAll();
public abstract void RemoveAll(Func<string, bool> removeExpression);
public abstract V this[string key] { get; }
}
}

最新文章

  1. 解析工具Goson
  2. BZOJ-1477 青蛙的约会 拓展欧几里德
  3. 成都Uber优步司机奖励政策(2月21日)
  4. java_Collection 类集
  5. Oracle EBS-SQL (WIP-13):检查任务组件未选MRP净值.sql
  6. ubuntu apt-get 遇到的问题
  7. net::ERR_CONNCTION_ABORTED与http post request header is too large 错误
  8. Surging微服务的注意事项
  9. Photoshop打造唯美的蓝色古装外景人物图片
  10. angular使用Md5加密
  11. 解决IE8不支持html5标签最好解决办法?
  12. Redis集群搭建(转自一菲聪天的“Windows下搭建Redis集群”)
  13. angularjs中ng-repeat插入图片
  14. [extjs] ExtJs4.2 Form 表单提交
  15. qemu网络虚拟化之数据流向分析二
  16. matplotlib对LaTeX数学公式的支持
  17. 洛谷 P3375 【模板】KMP字符串匹配
  18. 0053 用注解方式配置Spring MVC
  19. 利用Java编写简单的WebService实例
  20. 总结 一下UML 类图的关系

热门文章

  1. 使用Attiny 85开发板制作BadUSB
  2. Java中的synchronized
  3. C# 多线程系列(四)
  4. Deutsch lernen (04)
  5. DNN结构演进History—CNN-GoogLeNet :Going Deeper with Convolutions
  6. The remote certificate is invalid according to the validation procedure 远程证书验证无效
  7. javeee 字节Buffered
  8. snv报错
  9. eas之打开窗体
  10. 2019 gplt团体程序设计天梯赛总结