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> ...
随机推荐
- 【备份工具】mydumper
Mydumper主要特性:是一个针对MySQL的高性能多线程备份和恢复工具,开发人员主要来自MySQL,Facebook,SkySQL公司. 特性: 1:轻量级C语言写的 2:执行速度比mysqldu ...
- dubbo之事件通知
事件通知 在调用之前.调用之后.出现异常时,会触发 oninvoke.onreturn.onthrow 三个事件,可以配置当事件发生时,通知哪个类的哪个方法 1. 服务提供者与消费者共享服务接口 in ...
- VR: AR和VR演进哲学
Facebook 20亿美元(4亿美元+16亿美元股票换购方式)收购虚拟现实厂商Oculus 引爆AR产业,索尼不温不火逐步演进的头盔项目也该加速了.最近Oculus rift发布了商业版本:Ocul ...
- jQuery插件的怎么写
对于jQuery之前一直用,也看到过别人写的插件,直到最近才想着学习怎么写自己的jQuery插件,今天看了网上的一些资料,发现其实很简单的. 先看一个简单的jQuery插件的例子 <script ...
- 【汇编】dosbox钢琴
DATA SEGMENT msg DB 0DH,0AH,'[ 1 2 3 4 5 6 7 ]' DB 0DH,0AH,' [ q w e r t y u ]' DB 0DH,0AH,'________ ...
- HDU_3999_二叉排序树
The order of a Tree Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Othe ...
- Scala: Types of a higher kind
One of the more powerful features Scala has is the ability to generically abstract across things tha ...
- js 立即调用函数
function makeCounter() { //不能立即执行 // 只能在makeCounter内部访问i var i = 0; return function () { console.log ...
- 怎样在PDF文件中查找某个特定的词?
不得不说中国的修饰词太多了例如:“滚”可以这样说,请你以一种圆润的方式离开:上次小编在路上听到某男子打电话,好像是给女孩子,那口才,是真的牛,夸人不带重复的.要不是我男孩子,我都想以身相许了.人们常常 ...
- 继续聊WPF
下面看一个Tick控件的例子,这只是演示,Tick单独使用没有意义. <TickBar Height="15" Width="180" Ticks=&qu ...