一言不和就造轮子之 CookieHelper

2016-12-06
2分钟阅读时长

最近开始学 ASP.NET,然后发现 Cookie 的设置不像 PHP 简单粗暴(PHP Cookie用法),于是就造个轮子省事,注释很详细,这里就不再赘言。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;r

namespace BuildWheel
{
    /// <summary>
    /// Cookie辅助类
    /// </summary>
    public class CookieHelper
    {
        /// <summary>
        /// 设置、删除、修改cookie
        /// </summary>
        /// <param name="cookieName">cookie名称</param>
        /// <param name="cookieValue">cookie值</param>
        /// <param name="expires">过期时间</param>
        public static void SetCookie(string cookieName, string cookieValue, DateTime expires)
        {
            HttpCookie cookie = new HttpCookie(cookieName)
            {
                Value = cookieValue,
                Expires = expires
            };
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 删除指定cookie
        /// </summary>
        /// <param name="cookieName">cookie名称</param>
        public static void DeleteCookie(string cookieName)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName];
            if (cookie != null)
            {
                cookie.Expires = DateTime.Now.AddYears(-3);
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
        }

        /// <summary>
        /// 清除所有cookie
        /// </summary>
        public static void ClearCookies()
        {
            HttpContext.Current.Request.Cookies.AllKeys.ToList().ForEach((e) =>
            {
                HttpCookie cookie = HttpContext.Current.Response.Cookies[e];
                cookie.Expires = DateTime.Now.AddYears(-3);
                HttpContext.Current.Response.Cookies.Add(cookie);
            });
        }

        /// <summary>
        /// 获取cookie值
        /// </summary>
        /// <param name="cookieName">cookie名称</param>
        /// <returns></returns>
        public static string GetCookieValue(string cookieName)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName];
            string cookieValue = string.Empty;
            if (cookie != null)
            {
                cookieValue = cookie.Value;
            }
            return cookieValue;
        }
    }
}

有错误欢迎指出~

这是一篇过去很久的文章,其中的信息可能已经有所发展或是发生改变。

本文作者:她和她的猫
本文地址https://her-cat.com/posts/2016/12/06/cookie-helper-class/
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!