欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

asp.net的Cookie写入与读取

程序员文章站 2024-03-20 14:16:34
...

asp.net的Cookie写入与读取

1、什么是Cookie?

一段文本数据,默认存储在客户端,一种存放在浏览器缓存,一种存放在磁盘,最大可存储4kb。

2、怎么写入Cookie和读取Cookie?

(1)写入Cookie

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

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

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //写入cookie
            HttpCookie nc = new HttpCookie("newcookie");
            nc.Values["name"] = "ZhouXingXing";
            nc.Values["age"] = "27";
            nc.Values["dt"] = DateTime.Now.ToString();
            Response.Cookies.Add(nc);
            Response.Write("Cookie写入成功!");
        }
    }
}
    

(2)读取Cookie

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

namespace WebApplication2
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button22_Click(object sender, EventArgs e)
        {
            //读取Cookie
            HttpCookie getcook = Request.Cookies["newcookie"];
            Response.Write((getcook.Values["name"]));
            Response.Write("<br>" + getcook.Values["age"]);
            Response.Write("<br>" + getcook.Values["dt"]);
        }
    }
}
相关标签: asp.net知识收集