js中:
/** 记录Cookie */
function setCookie(name, value, expireHours) {
var cookieString = name + "=" + encodeURIComponent(value);
//判断是否设置过期时间
if (expireHours > 0) {
var date = new Date();
date.setTime(date.getTime() + expireHours * 3600 * 1000);
cookieString = cookieString + "; expire=" + date.toGMTString();
}
document.cookie = cookieString;
}
/** 获取Cookie */
function getCookie(name) {
var cookies = document.cookie;
var list = cookies.split("; "); // 解析出名/值对列表
for (var i = 0; i < list.length; i++) {
var arr = list[i].split("="); // 解析出名和值
if (arr[0] == name) {
return decodeURIComponent(arr[1]); // 对cookie值解码
}
}
return "";
}
/** 清除Cookie */
function delCookie(name) {
setCookie(name, "", 0);
}
C#中:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Caching;
/// <summary>
/// Cookie 的摘要说明
/// </summary>
public class Cookie
{
/// <summary>
/// 记录到服务器缓存
/// </summary>
public static void SaveCache(string key, object value, int expireMinute = 1440) {
DateTime expireTime = DateTime.Now.AddMinutes(expireMinute);
HttpContext.Current.Cache.Add(key, value, null, expireTime, Cache.NoSlidingExpiration, CacheItemPriority.High, null);
}
/// <summary>
/// 从服务器缓存获取数据
/// </summary>
public static object GetCache(string key)
{
return HttpContext.Current.Cache.Get(key);
}
/// <summary>
/// 记录到客户端缓存
/// </summary>
public static void SaveCookie(string key, string value, int expireMinute = 1440)
{
HttpCookie ck = new HttpCookie(key, value);
ck.Expires = DateTime.Now.AddMinutes(expireMinute);
HttpContext.Current.Response.Cookies.Add(ck);
}
/// <summary>
/// 从客户端缓存获取数据
/// </summary>
public static string GetCookie(string key)
{
string data = "";
HttpCookie ck = HttpContext.Current.Request.Cookies[key];
if(ck != null) data = ck.Value;
return data;
}
}