ASP.NET - Cookie

ASP.NET - Cookie 首页 / ASP.Net MVC入门教程 / ASP.NET - Cookie

ASP.NET Cookie是用于存储用户特定信息的一小段文本。每当用户访问该站点时,Web应用程序都可以读取该信息。

当用户请求网页时,Web服务器不仅发送页面,还发送包含日期和时间的cookie。此Cookie存储在用户硬盘上的文件夹中。

当用户再次请求网页时,浏览器在硬盘上查找与该网页相关联的cookie。浏览器为每个用户访问的不同站点存储单独的cookie。

Note: Cookie限制为小尺寸,可用于仅存储4 kB(4096字节)的文本。

在ASP.NET应用程序中存储Cookie有两种方式。

  • Cookies collection
  • HttpCookie

可以将Cookie添加到Cookies集合中,也可以通过创建HttpCookie类的实例来添加。两者的工作原理相同,只是HttpCookie需要Cookie名称作为构造函数的一部分。

HttpCookie示例

在下面的示例中,将在HttpCookie类的帮助下创建和添加Cookie。

//CookieExample.aspx

<%@ Page Language="C#" AutoEventWireup="true" 
代码Behind="CookieExample.aspx.cs" Inherits="CoockieExample.CookieExample" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        </div>
    </form>
</body>
</html>

代码

//CookieExample.aspx.cs

using System;
using System.Web;
namespace WebFormsControlls
{
    public partial class CookieExample : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //-------------- Creating Cookie --------------------------//
            // Creating HttpCookie instance by specifying name "student"
                HttpCookie cokie = new HttpCookie("student");
            // Assigning value to the created cookie
                cokie.Value = "Rahul Kumar";
            // Adding Cookie to the response instance
                Response.Cookies.Add(cokie);
            //--------------- Fetching Cookie -------------------------//
            var co_val  = Response.Cookies["student"].Value;
            Label1.Text = co_val;
        }
    }
}

Cookie集合示例

在下面的示例中,无涯教程将Cookie直接添加到Cookies集合。

//Default.aspx

<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" 代码Behind="Default.aspx.cs"
Inherits="CoockieExample._Default" %>
<form id="form1" runat="server">
    <asp:Label ID="Label1" runat="server" Text="Select Brand Preferences"></asp:Label>
    <br />
    <br />
    <asp:CheckBox ID="apple" runat="server" Text="Apple" />
    <br />
    <asp:CheckBox ID="dell" runat="server" Text="Dell" />
    <br />
    <asp:CheckBox ID="lenevo" runat="server" Text="Lenevo" />
    <br />
    <asp:CheckBox ID="acer" runat="server" Text="Acer" />
    <br />
    <asp:CheckBox ID="sony" runat="server" Text="Sony" />
    <br />
    <asp:CheckBox ID="wipro" runat="server" Text="Wipro" />
    <br />
    <br />
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
    <p>
        <asp:Label ID="Label2" runat="server"></asp:Label>
    </p>
</form>

//Default.aspx.cs

using System;
using System.Web.UI;
namespace CoockieExample
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Setting expiring date and time of the cookies
            Response.Cookies["computer"].Expires = DateTime.Now.AddDays(-1);
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            Label2.Text = "";
            // --------------- Adding Coockies ---------------------//
            if (apple.Checked)
                Response.Cookies["computer"]["apple"]  = "apple";
            if (dell.Checked)
                Response.Cookies["computer"]["dell"]   = "dell";
            if (lenevo.Checked)
                Response.Cookies["computer"]["lenevo"] = "lenevo";
            if (acer.Checked)
                Response.Cookies["computer"]["acer"]   = "acer";
            if (sony.Checked)
                Response.Cookies["computer"]["sony"]   = "sony";
            if (wipro.Checked)
                Response.Cookies["computer"]["wipro"]  = "wipro";
            // --------------- Fetching Cookies -----------------------//
            if (Request.Cookies["computer"].Values.ToString() != null)
            {
                if (Request.Cookies["computer"]["apple"] != null)
                    Label2.Text += Request.Cookies["computer"]["apple"] + " ";
                if (Request.Cookies["computer"]["dell"] != null)
                    Label2.Text += Request.Cookies["computer"]["dell"] + " ";
                if (Request.Cookies["computer"]["lenevo"] != null)
                    Label2.Text += Request.Cookies["computer"]["lenevo"] + " ";
                if (Request.Cookies["computer"]["acer"] != null)
                    Label2.Text += Request.Cookies["computer"]["acer"] + " ";
                if (Request.Cookies["computer"]["sony"] != null)
                    Label2.Text += Request.Cookies["computer"]["sony"] + " ";
                if (Request.Cookies["computer"]["wipro"] != null)
                    Label2.Text += Request.Cookies["computer"]["wipro"] + " ";
            }else Label2.Text = "Please select your choice";
            Response.Cookies["computer"].Expires = DateTime.Now.AddDays(-1);
        }
    }
}

输出:

此示例将所选值存储为Cookie。

ASP Net Cookie 1ASP Net Cookie 2

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

推荐系统三十六式 -〔刑无刀〕

MySQL实战45讲 -〔林晓斌〕

Linux实战技能100讲 -〔尹会生〕

ZooKeeper实战与源码剖析 -〔么敬国〕

大厂晋升指南 -〔李运华〕

攻克视频技术 -〔李江〕

郭东白的架构课 -〔郭东白〕

深入浅出分布式技术原理 -〔陈现麟〕

徐昊 · TDD项目实战70讲 -〔徐昊〕

好记忆不如烂笔头。留下您的足迹吧 :)