ASP.NET -- WebForm -- Cookie的使用

时间:2023-03-08 23:07:04
ASP.NET -- WebForm --  Cookie的使用

ASP.NET -- WebForm --  Cookie的使用

Cookie是存在浏览器内存或磁盘上。

1. Test3.aspx文件

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test3.aspx.cs" Inherits="Test3" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

2. Test3.aspx.cs文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; public partial class Test3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.Cookies["myProject"] != null)
{
//如果浏览器端发送给服务器端的Cookie有'myProject',则显示'myProject'的Cookie值
Label1.Text = Request.Cookies["myProject"].Value;
}
else
{
//如果浏览器端发送给服务器端的Cookie没有'myProject',则设置'myProject'的Cookie值
Response.Cookies["myProject"].Value = "Test3";
//没有设置过期时间的cookie是存在浏览器内存中的,浏览器关闭就会消失 //设置了过期时间的cookie,关闭浏览器也不消失,是存在浏览器所使用的磁盘文件上的
//设置cookie的有效期为一天, 该cookie一天后就会失效
//Response.Cookies["myProject"].Expires = DateTime.Now.AddDays(1);
}
}
}
}

3. 实现结果

(1) 首次访问页面,没有cookie值,则设置cookie的值,服务器通过响应报文把要设置的cookie发送给浏览器。

ASP.NET -- WebForm --  Cookie的使用

(2) 再次访问页面时。浏览器会将cookie放在发送报文中,发送给服务器端。服务器端可将接收到的cookie值显示出来。

ASP.NET -- WebForm --  Cookie的使用