Cookie帮助类


/// Cookie帮助类
public class CookieUtils
{
  /// 写cookie值
  public static void WriteCookie(string strName, string strValue)
  {
    HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
    if (cookie == null)
    {
      cookie = new HttpCookie(strName);
    }
    cookie.Value = strValue;
    HttpContext.Current.Response.AppendCookie(cookie);
  }

  /// 写cookie值
  /// <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.Path = "/";
    cookie.Value = strValue;
    cookie.Expires = DateTime.Now.AddMinutes(expires);
    HttpContext.Current.Response.AppendCookie(cookie);
  }

  /// 读cookie值
  public static string GetCookie(string strName)
  {
    if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
    {
      return HttpContext.Current.Request.Cookies[strName].Value.ToString();
    }
    return "";
  }

  /// 删除Cookie对象
  public static void DelCookie(string CookiesName)
  {
    HttpCookie objCookie = new HttpCookie(CookiesName.Trim());
    objCookie.Expires = DateTime.Now.AddYears(-5);
    HttpContext.Current.Response.Cookies.Add(objCookie);
  }
}

posted @ 2018-07-06 15:54  GU天乐乐乐!  阅读(161)  评论(1编辑  收藏  举报