码迷,mamicode.com
首页 > Windows程序 > 详细

C#中Cookies的存取

时间:2014-11-23 01:58:10      阅读:289      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   on   

<1>

C#中Cookies的存取

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

namespace WebApplication1
{
    public class FunCookie
    {
        /// <summary>
        /// 创建Cookie和赋值,及设计Cookie有效天数
        /// </summary>
        /// <param name="strCookieName">Cookie名字</param>
        /// <param name="strCookieValue">Cookie的值</param>
        /// <param name="intDay">Cookie有效天数</param>
        /// <returns>布尔值</returns>
        public static bool SetCookie(string strCookieName,string strCookieValue,int intDay )
        {
            try
            {
                HttpCookie cookie = new HttpCookie(strCookieName); //创建一个cookie对象
                cookie.Value = strCookieValue; //设置cookie的值
                cookie.Expires = DateTime.Now.AddDays(intDay); //或cookie.Expires.AddDays(intDay);设置cookie的有效期
                System.Web.HttpContext.Current.Response.Cookies.Add(cookie); //将cookie添加到cookies中
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 根据Cookie的名字获取Cookie的值
        /// </summary>
        /// <param name="strCookieName">要获取的Cookie的名字</param>
        /// <returns>Cookie的值(string类型)</returns>
        public static string GetCookie(string strCookieName)
        {
            HttpCookie cookie= HttpContext.Current.Request.Cookies[strCookieName];//获取cookie
            if (cookie != null)
            {
                return cookie.Value; //返回cookie的值
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 删除Cookie
        /// </summary>
        /// <param name="strCookieName"></param>
        /// <returns></returns>
        public static bool DeleteCookie(string strCookieName)
        {
            try
            {
                HttpCookie cookie = new HttpCookie(strCookieName);
                cookie.Expires = DateTime.Now.AddDays(-1); 
                HttpContext.Current.Response.Cookies.Add(cookie);
                return true;
            }
            catch
            {
                return false;
            }
        }

        
    }
}


C#中Cookies的存取

标签:style   blog   http   io   ar   color   os   sp   on   

原文地址:http://blog.csdn.net/fanbin168/article/details/41398677

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