主要用于.NET ASP MVC获取或者设置Cookie
1、保存Cookie
public void SaveCookie(string uid, string passwd)
{
int time = Time.GetUnixTime();
string md5Passwd = Encrypt.MD5(passwd);
string key = Base64.Base64Encode(uid + ":" + md5Passwd + ":" + time);
//添加此cookie
HttpCookie cook = new HttpCookie("USER");
cook.Expires = DateTime.Now.AddDays(15);
cook.Values.Set("KEY", key);
cook.HttpOnly = true;
Response.Cookies.Add(cook);
}
2、获取Cookie
HttpCookie cook = Request.Cookies["USER"];
3、清除Cookie
/// <summary>
/// 清除Cookie
/// </summary>
/// <param name="cookie"></param>
public void CookieClear(HttpCookie cookie)
{
if (cookie != null)
{
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
}
else
{
HttpCookie cook = new HttpCookie("USER");
cook.Expires = DateTime.Now.AddDays(-1);
cook.Values.Set("KEY", "");
Response.Cookies.Add(cook);
}
}
4、关于Cookie的生命周期
4.1 一定的时间失效
cook.Expires = DateTime.Now.AddDays(15); //15天失效
4.2 当前浏览器窗口有效,关闭浏览器失效
cook.Expires = DateTime.MinValue; //表示关闭浏览器过期
4.3 立即失效
cook.Expires = DateTime.Now.AddDays(-1);
文章评论