您的位置:首页 > 其它

购物车之服务器端操作Cookie 实例

2007-11-14 13:57 585 查看
public class Cookie

{

public static readonly string strcolumen = " or bkpzid='";

public static string readCookie()

{

string coo = "";

string sql = "";

if (HttpContext.Current.Request.Cookies["dyid"] != null)

{

coo = HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request.Cookies["dyid"].Value);

}

string[] varstr = coo.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);

for (int i = 0; i < varstr.Length; i++)

{

if (i == 0)

{

sql = varstr[i].ToString() + "'";

}

else

{

sql += strcolumen + varstr[i].ToString() + "' ";

}

}

return sql;

}

public static void writeCookie(string id)

{

//判断是否存在Cookie

bool flag = false;

string coo = "";

//判断Coolie在硬盘上是否存在,存在就用request 取出Cookie,不存在就创建Cookie

if (HttpContext.Current.Request.Cookies["dyid"] != null)

{

coo = HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request.Cookies["dyid"].Value);

string[] varstr = coo.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);

//判断Coolie的值是否为空字符串,做特殊处理

if (coo == "")

{

flag = true;

}

for (int i = 0; i < varstr.Length; i++)

{

if (id.ToUpper() == varstr[i].ToString())

{

//存在

flag = false;

break;

}

else

{

flag = true;

}

}

if (flag)

{

coo = coo + id + ",";

HttpCookie dycookie = HttpContext.Current.Request.Cookies["dyid"];

dycookie.Value = HttpContext.Current.Server.UrlEncode(coo);

dycookie.Expires = System.DateTime.Now.AddDays(7);

HttpContext.Current.Response.Cookies.Add(dycookie);

}

}

else

{

coo = id + ",";

HttpCookie dycookie = new HttpCookie("dyid");

dycookie.Value = HttpContext.Current.Server.UrlEncode(coo);

dycookie.Expires = System.DateTime.Now.AddDays(7);

HttpContext.Current.Response.Cookies.Add(dycookie);

}

}

/// <summary>

/// 针对 CLOSE 按钮删除COOKIE

/// </summary>

/// <param name="id"></param>

public static string updateCookie(string id)

{

string coo = "";

string value = "";

if(HttpContext.Current.Request.Cookies["dyid"] != null)

{

coo = HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request.Cookies["dyid"].Value);

}

string[] varstr = coo.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);

for (int i = 0; i < varstr.Length; i++)

{

if (id.ToUpper() == varstr[i].ToString())

{

i++;

}

if (i < varstr.Length)

{

value += varstr[i] + ",";

}

}

HttpCookie dycookie = HttpContext.Current.Request.Cookies["dyid"];

dycookie.Value = HttpContext.Current.Server.UrlEncode(value);

dycookie.Expires = System.DateTime.Now.AddDays(7);

HttpContext.Current.Response.Cookies.Add(dycookie);

return readCookie();

}

public static void deleteCookie()

{

//删除Cookie 与创建 Cookie的方法相同,只需要把时间设置为过去某一个时刻。

HttpCookie dycookie = new HttpCookie("dyid");

dycookie.Value = "1";

dycookie.Expires = System.DateTime.Now.AddDays(-1);

HttpContext.Current.Response.Cookies.Add(dycookie);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: