cookie 为什么设置了过期时间 不起作用 浏览器关闭 cookie 就没了

刚开始用火狐测试,设置后 马上读取 可以读取到cookie  关闭浏览器之后cookie 就没了

在ie 等其它浏览器可以正常读取,只有火狐不行

1:因为我的火狐设置了不记录浏览历史记录,所以cookie关闭浏览器就失效了,无论你怎么在代码里设置时间都没用

解决方法 工具-选项-隐私  历史记录设置成记录历史记录

cookie 为什么设置了过期时间 不起作用 浏览器关闭 cookie 就没了_第1张图片


测试cookie


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="emptyWebApplication1.WebForm1" %>





   
   


   


       

           
            
       

   



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

namespace emptyWebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                if (Request.Cookies["MyCook"] != null && !string.IsNullOrEmpty(Request.Cookies["MyCook"].Value))
                {
                    Response.Write("IsPostBack"+Request.Cookies["MyCook"].Value); //输出为:userid=userid_value&userid2=userid2_value2
                }
                else
                {
                    Response.Write("IsPostBack没有mycook" ); //输出为:userid=userid_value&userid2=userid2_value2
                   
                }
            }
        }

        //读取
        protected void Button1_Click(object sender, EventArgs e)
        {

            // HttpCookie cokie = new HttpCookie("MyCook");//初使化
            if (Request.Cookies["MyCook"] != null)
            {
                //Response.Write("Cookie中键值为userid的值:" + Request.Cookies["MyCook"]["userid"]);//整行
                //Response.Write("Cookie中键值为userid2的值" + Request.Cookies["MyCook"]["userid2"]);
                Response.Write(Request.Cookies["MyCook"].Value);//输出全部的值
            }
        }
        //读取
        protected void Button2_Click(object sender, EventArgs e)
        {
           
            HttpCookie cookie = new HttpCookie("MyCook");//初使化并设置Cookie的名称
            DateTime dt = DateTime.Now;
            cookie.Expires = DateTime.Now.AddDays(1); ;//设置过期时间
            cookie.Values.Add("userid", "userid_value");
            cookie.Values.Add("userid2", "userid2_value2");
            cookie.Path = "/";
            Response.Cookies.Add(cookie);
            输出该Cookie的所有内容
            //Response.Write(cookie.Value); //输出为:userid=userid_value&userid2=userid2_value2
        }
    }
}

你可能感兴趣的:(Cookie)