天天看點

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>      

View Code

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的使用

轉載于:https://www.cnblogs.com/ChengWenHao/p/AspNetPart5.html