<1>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication1
{
public class FunCookie
{
/// <summary>
/// 创建Cookie和赋值,及设计Cookie有效天数
/// </summary>
/// <param name="strCookieName">Cookie名字</param>
/// <param name="strCookieValue">Cookie的值</param>
/// <param name="intDay">Cookie有效天数</param>
/// <returns>布尔值</returns>
public static bool SetCookie(string strCookieName,string strCookieValue,int intDay )
{
try
{
HttpCookie cookie = new HttpCookie(strCookieName); //创建一个cookie对象
cookie.Value = strCookieValue; //设置cookie的值
cookie.Expires = DateTime.Now.AddDays(intDay); //或cookie.Expires.AddDays(intDay);设置cookie的有效期
System.Web.HttpContext.Current.Response.Cookies.Add(cookie); //将cookie添加到cookies中
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 根据Cookie的名字获取Cookie的值
/// </summary>
/// <param name="strCookieName">要获取的Cookie的名字</param>
/// <returns>Cookie的值(string类型)</returns>
public static string GetCookie(string strCookieName)
{
HttpCookie cookie= HttpContext.Current.Request.Cookies[strCookieName];//获取cookie
if (cookie != null)
{
return cookie.Value; //返回cookie的值
}
else
{
return null;
}
}
/// <summary>
/// 删除Cookie
/// </summary>
/// <param name="strCookieName"></param>
/// <returns></returns>
public static bool DeleteCookie(string strCookieName)
{
try
{
HttpCookie cookie = new HttpCookie(strCookieName);
cookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Cookies.Add(cookie);
return true;
}
catch
{
return false;
}
}
}
}原文:http://blog.csdn.net/fanbin168/article/details/41398677