C#操作Cookie

/* 创建者:菜刀居士的博客
 * 创建日期: 2014年09月02号
 * 功能:操作Cookie
 *
 */

namespace Net.String.ConsoleApplication
{
    using System;
    using System.Web;

    public static class CookieHelper
    {
        /// <summary>
        /// 添加cookie
        /// </summary>
        public static void AddCookie(this HttpContext h,string name, string value)
        {
            HttpCookie cookieName = new HttpCookie(name, System.Web.HttpUtility.UrlEncode(value, System.Text.Encoding.GetEncoding(65001)));
            h.Response.Cookies.Add(cookieName);
        }

        /// <summary>
        /// 添加cookie
        /// </summary>
        public static void AddCookie(this HttpContext h,string name, string value, TimeSpan span)
        {
            HttpCookie cookieName = new HttpCookie(name, System.Web.HttpUtility.UrlEncode(value, System.Text.Encoding.GetEncoding(65001)));

            cookieName.Expires = DateTime.Now.Add(span);

            h.Response.Cookies.Add(cookieName);
        }

        /// <summary>
        /// 得到cookie
        /// </summary>
        public static string GetCookie(this HttpContext h, string name)
        {
            if (h.Request.Cookies[name] != null)
            {
                if (h.Response.Cookies.Count > 0 && h.Response.Cookies[name] != null)
                {
                    return System.Web.HttpUtility.UrlDecode(h.Response.Cookies[name].Value, System.Text.Encoding.GetEncoding(65001));
                }
                return System.Web.HttpUtility.UrlDecode(h.Request.Cookies[name].Value, System.Text.Encoding.GetEncoding(65001));
            }
            else
            { return string.Empty; }
        }

        /// <summary>
        /// 删除cookie
        /// </summary>
        public static void RemoveCookie(this HttpContext h,string name)
        {
            h.Response.Cookies[name].Value = null;
            h.Response.Cookies[name].Expires = DateTime.Now.AddDays(-1);
        }

        /// <summary>
        /// 清空cookie
        /// </summary>
        public static void ClearCookie(this HttpContext h)
        {
            try
            {
                foreach (HttpCookie hc in h.Response.Cookies)
                {
                    hc.Value = null;
                    hc.Expires = DateTime.Now.AddDays(-1);
                }
            }
            catch { }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值