码迷,mamicode.com
首页 > 其他好文 > 详细

C#操作Cookie

时间:2014-09-02 09:06:34      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:c#操作cookie   asp.net操作cookie   asp.net自定义开发   c#开发   asp.net   

/* 创建者:菜刀居士的博客
 * 创建日期: 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 { }
        }
    }
}

C#操作Cookie

标签:c#操作cookie   asp.net操作cookie   asp.net自定义开发   c#开发   asp.net   

原文地址:http://blog.csdn.net/y_f123/article/details/39000915

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!