实现代码:

//声名一个数据集合
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; }
}
}

Cookies操作类的更多相关文章

  1. C#语法糖之Cookies操作类 asp.net

    用法: //声名一个数据集合 var listString = new List<string>() { "a", "b", "c&quo ...

  2. C#语法糖之 cache操作类 asp.net

    因为考虑到我下面我将写session cookies 等 操作类 ,与cache具有共性. 所以都统一继承了IHttpStorageObject  abstract class 来保函数风格的统一 , ...

  3. Cookie操作类 实现记住用户名和密码的功能

    import java.util.Hashtable;import java.util.Iterator;import java.util.Set;import javax.servlet.http. ...

  4. 【PHPsocket编程专题(实战篇②)】兼容 Curl/Socket/Stream 的 HTTP 操作类[转]

    <?php /************************************************************ * 描述:HTTP操作类 * 作者:heiyeluren ...

  5. session操作类

    using System;using System.Web; /// <summary> ///session操作类 /// </summary> public class a ...

  6. Cookie操作类、 包括创建、读取、修改、获取、销毁cookie

    Cookie操作类. 包括创建.读取.修改.获取.销毁cookie import java.util.Hashtable; import java.util.Iterator; import java ...

  7. 【知识必备】ezSQL,最好用的数据库操作类,让php操作sql更简单~

    最近用php做了点小东东,用上了ezSQL,感觉真的很ez,所以拿来跟大家分享一下~ ezSQL是一个非常好用的PHP数据库操作类.著名的开源博客WordPress的数据库操作就使用了ezSQL的My ...

  8. JQuery操作类数组的工具方法

    JQuery学习之操作类数组的工具方法 在很多时候,JQuery的$()函数都返回一个类似数据的JQuery对象,例如$('div')将返回div里面的所有div元素包装的JQuery对象.在这中情况 ...

  9. Util应用程序框架公共操作类(十二):Lambda表达式公共操作类(三)

    今天在开发一个简单查询时,发现我的Lambda操作类的GetValue方法无法正确获取枚举类型值,以至查询结果错误. 我增加了几个单元测试来捕获错误,代码如下. /// <summary> ...

随机推荐

  1. SQLServer 里的三种条件判断的用法:Where GroupBy Having

    HAVING 子句对 GROUP BY 子句设置条件的方式与 WHERE 子句和 SELECT 语句交互的方式类似.WHERE 子句搜索条件在进行分组操作之前应用:而 HAVING 搜索条件在进行分组 ...

  2. 安装sql server 2008 R2出现 创建usersettings/microsoft.sqlserver.configuration.landingpage.properties.setter

    造成这个原因是由于先装了VS(我之前安装的是vs2012)开发环境造成的,需要删除 路径为 C:\Users\Administrator\AppData\Local\Microsoft_Corpora ...

  3. OpenCV:OpenCV图像旋转的代码

    OpenCV图像旋转的代码 cv::transpose( bfM, bfM ) 前提:使用两个矩阵Mat型进行下标操作是不行的,耗费的时间太长了.直接使用两个指针对拷贝才是王道.不知道和OpenCV比 ...

  4. html中的小知识

    引用外部样式 样式表,如果是引用外部样式,不需要再写style标签了,因为 <link rel="stylesheet" type="text/css" ...

  5. python 处理中文 读取数据库输出全是问号

    ref:http://www.cnblogs.com/zhoujie/archive/2013/06/07/problem1.html 1.python连接mssql数据库编码问题 python一直对 ...

  6. vue中需要注意的问题总结(上)

    React 与其说是一种框架,倒不如说是一种开发范式.它的核心理念非常简单: 界面/视图就是数据结构的可视化表达UI = f(data) 而界面/视图由组件组合而来UI = f1(data) + f2 ...

  7. rabbitmq和kafka的区别

    1.吞吐量kafka吞吐量更高: 1)Zero Copy机制,内核copy数据直接copy到网络设备,不必经过内核到用户再到内核的copy,减小了copy次数和上下文切换次数,大大提高了效率. 2)磁 ...

  8. Git创建本地分支并关联远程分支(二)

    创建本地分支git branch 分支名 例如:git branch dev,这条命令是基于当前分支创建的本地分支,假设当前分支是master(远程分支),则是基于master分支创建的本地分支dev ...

  9. eas之style接口

    Obj可以是KDTable对象,也可以是IRow,IColumn,ICell对象锁定Obj.getStyleAttributes().setLocked(true);Obj.getStyleAttri ...

  10. eas之去掉关闭eas页面时校验是否修改的提示

    EditUI-------> public boolean checkBeforeWindowClosing() {            boolean b = super.checkBefo ...