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

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

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

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

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


测试cookie


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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button runat="server" ID="test" Text="读取cookie" OnClick="Button1_Click" />
             <asp:Button runat="server" ID="Button1" Text="设置cookie" OnClick="Button2_Click" />
        </div>
    </form>
</body>
</html>


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
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值