Cookies操作类
实现代码:
//声名一个数据集合
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操作类的更多相关文章
- C#语法糖之Cookies操作类 asp.net
用法: //声名一个数据集合 var listString = new List<string>() { "a", "b", "c&quo ...
- C#语法糖之 cache操作类 asp.net
因为考虑到我下面我将写session cookies 等 操作类 ,与cache具有共性. 所以都统一继承了IHttpStorageObject abstract class 来保函数风格的统一 , ...
- Cookie操作类 实现记住用户名和密码的功能
import java.util.Hashtable;import java.util.Iterator;import java.util.Set;import javax.servlet.http. ...
- 【PHPsocket编程专题(实战篇②)】兼容 Curl/Socket/Stream 的 HTTP 操作类[转]
<?php /************************************************************ * 描述:HTTP操作类 * 作者:heiyeluren ...
- session操作类
using System;using System.Web; /// <summary> ///session操作类 /// </summary> public class a ...
- Cookie操作类、 包括创建、读取、修改、获取、销毁cookie
Cookie操作类. 包括创建.读取.修改.获取.销毁cookie import java.util.Hashtable; import java.util.Iterator; import java ...
- 【知识必备】ezSQL,最好用的数据库操作类,让php操作sql更简单~
最近用php做了点小东东,用上了ezSQL,感觉真的很ez,所以拿来跟大家分享一下~ ezSQL是一个非常好用的PHP数据库操作类.著名的开源博客WordPress的数据库操作就使用了ezSQL的My ...
- JQuery操作类数组的工具方法
JQuery学习之操作类数组的工具方法 在很多时候,JQuery的$()函数都返回一个类似数据的JQuery对象,例如$('div')将返回div里面的所有div元素包装的JQuery对象.在这中情况 ...
- Util应用程序框架公共操作类(十二):Lambda表达式公共操作类(三)
今天在开发一个简单查询时,发现我的Lambda操作类的GetValue方法无法正确获取枚举类型值,以至查询结果错误. 我增加了几个单元测试来捕获错误,代码如下. /// <summary> ...
随机推荐
- Redis学习笔记(四)-数据类型之list类型
redis的list类型其实就是一个每个子元素都是string类型的双向链表.所以[lr]push和[lr]pop命令的算法时间复杂度都是O(1).另外list会记录链表的长度.所以llen操作也是O ...
- HTML+CSS(11)
n CSS背景属性 Background-color:背景色. Background-image:背景图片地址.如:background-image:url(images/bg.gif;) Back ...
- Android开发笔记(12)——ListView & Adapter
转载请注明:http://www.cnblogs.com/igoslly/p/6947225.html 下一章是关于ListFragment的内容,首先先介绍ListView的相关配置,理解ListF ...
- 浅谈ByteBuffer转换成byte[]时遇到的问题
有些时候我们要把ByteBuffer转换成byte[]来使用.于是很多时候会用以下代码来转换: ByteBuffer buf; .....(一些往buffer写数据的操作) byte[] bs= ne ...
- PCL的学习必要性、重要性、意义及最初——持续修改中
为什么学习PCL:图像描述:各种维度图像的逻辑描述形式 ^-^ 且点云库是机器人学领域的必备基础库,ICRA和IROS的计算机视觉相关一般都使用了PCL库,PCL库也成为ROS的基础部分,与机器人操 ...
- 简单servlet调用dao层完整步骤
导入包lib(文件名称) 目录结构:web下:views.web-inf.index.jsp views下各种jsp文件和js(里面放封装好的jquery包) js下:jquery包(js文件后缀) ...
- jdk?jre?
很多人都搞不懂什么是jdk,什么是jre,只知道电脑安装了这两个就能开发和运行java程序,这里我简单讲讲什么是jdk,什么是jre. jdk,即Java Development Kit,故名思意就是 ...
- 学习Spider 了解 Scrapy的流程
Scrapy 先创建项目 在windows下 scrapy startproject myproject #myproject是你的项目名称 cd 项目名称 scrapy g ...
- 什么是Capability
desired capability的功能是配置Appium会话.他们告诉Appium服务器您想要自动化的平台和应用程序. Desired Capabilities是一组设置的键值对的集合,其中键对应 ...
- Mark Zuckberg: A letter to our daughter
转自: http://www.fastcompany.com/3054120/fast-feed/read-mark-zuckerbergs-letter-to-his-newborn-daugh ...