C#,添加,读取,清除Cookie

20180530更新

/// <summary>
/// 写cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <param name="strValue">值</param>
/// <param name="strValue">过期时间(分钟)</param>
public static void WriteCookie(string strName, string strValue, int expires)
{
    HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
    if (cookie == null)
    {
        cookie = new HttpCookie(strName);
    }
    cookie.Value = UrlEncode(strValue);
    cookie.Expires = DateTime.Now.AddMinutes(expires);
    HttpContext.Current.Response.AppendCookie(cookie);
}
 
 
/// <summary>
/// 取得CookieValue
/// </summary>
/// <param name="CookieName">Cookie名称</param>
/// <returns>Cookie的值</returns>
public static string GetCookie(string CookieName)
{
    HttpCookie myCookie = new HttpCookie(CookieName);
    myCookie = HttpContext.Current.Request.Cookies[CookieName];
 
    if (myCookie != null)
        return myCookie.Value;
    else
        return null;
}
 
 
/// <summary>
/// 清除CookieValue
/// </summary>
/// <param name="CookieName">Cookie名称</param>
public static void RemoveCookie(string CookieName)
{
    HttpCookie myCookie = new HttpCookie(CookieName);
    DateTime now = DateTime.Now;
 
    myCookie.Expires = now.AddYears(-2);
 
    HttpContext.Current.Response.Cookies.Add(myCookie);
}


评论