ASP.NET Cookie

  最经在使用Cookie的过程中遇到了一些疑问,查阅参考MSDN,记录Cookie相关知识点

什么是Cookie

  Cookie是一小段文本信息,伴随着用于的请求和页面在Web服务器和浏览器之间传递,并将它存储在用户硬盘上的某个文件夹中。Cookie包含每次用户访问站点时Web应用程序都可以读取的信息。以后,如果用户在此请求特定站点中的页面,当用户输入特定URL时,浏览器会在本地硬盘上查找与该URL关联的Cookie。如果该Cookie存在,浏览器将该Cookie与页面请求一起发送到你的站点。Cookie与网站关联,而不是与特定页面关联。因此,无论用户请求站点中的哪一个页面,浏览器和服务器都交换Cookie信息。用户访问不同站点时,各个站点都可能会向用户浏览器发送一个Cookie,浏览器会分别存储所有Cookie。

Cookie限制

  大多数浏览器支持最大为4096字节的Cookie,这限制了Cookie的大小,最好用Cookie来存放少量的数据。浏览器还限制站点可以在用户计算机上存储的Cookie的数量。大多数浏览器只允许每个站点存储20个Cookie。如果试图存储更多Cookie,则最旧的Cookie便会被丢弃。有些浏览器还会对他们将接受的来自所有站点的Cookie总数做出绝对限制,通常为300个。

Cookie类定义

    // Summary:
    //     Provides a type-safe way to create and manipulate individual HTTP cookies.
    public sealed class HttpCookie
    {
        // Summary:
        //     Creates and names a new cookie.
        //
        // Parameters:
        //   name:
        //     The name of the new cookie.
        public HttpCookie(string name);
        //
        // Summary:
        //     Creates, names, and assigns a value to a new cookie.
        //
        // Parameters:
        //   name:
        //     The name of the new cookie.
        //
        //   value:
        //     The value of the new cookie.
        public HttpCookie(string name, string value);

        // Summary:
        //     Gets or sets the domain to associate the cookie with.
        //
        // Returns:
        //     The name of the domain to associate the cookie with. The default value is
        //     the current domain.
        public string Domain { get; set; }
        //
        // Summary:
        //     Gets or sets the expiration date and time for the cookie.
        //
        // Returns:
        //     The time of day (on the client) at which the cookie expires.
        public DateTime Expires { get; set; }
        //
        // Summary:
        //     Gets a value indicating whether a cookie has subkeys.
        //
        // Returns:
        //     true if the cookie has subkeys, otherwise, false. The default value is false.
        public bool HasKeys { get; }
        //
        // Summary:
        //     Gets or sets a value that specifies whether a cookie is accessible by client-side
        //     script.
        //
        // Returns:
        //     true if the cookie has the HttpOnly attribute and cannot be accessed through
        //     a client-side script; otherwise, false. The default is false.
        public bool HttpOnly { get; set; }
        //
        // Summary:
        //     Gets or sets the name of a cookie.
        //
        // Returns:
        //     The default value is a null reference (Nothing in Visual Basic) unless the
        //     constructor specifies otherwise.
        public string Name { get; set; }
        //
        // Summary:
        //     Gets or sets the virtual path to transmit with the current cookie.
        //
        // Returns:
        //     The virtual path to transmit with the cookie. The default is the path of
        //     the current request.
        public string Path { get; set; }
        //
        // Summary:
        //     Gets or sets a value indicating whether to transmit the cookie using Secure
        //     Sockets Layer (SSL)--that is, over HTTPS only.
        //
        // Returns:
        //     true to transmit the cookie over an SSL connection (HTTPS); otherwise, false.
        //     The default value is false.
        public bool Secure { get; set; }
        //
        // Summary:
        //     Gets or sets an individual cookie value.
        //
        // Returns:
        //     The value of the cookie. The default value is a null reference (Nothing in
        //     Visual Basic).
        public string Value { get; set; }
        //
        // Summary:
        //     Gets a collection of key/value pairs that are contained within a single cookie
        //     object.
        //
        // Returns:
        //     A collection of cookie values.
        public NameValueCollection Values { get; }

        // Summary:
        //     Gets a shortcut to the System.Web.HttpCookie.Values property. This property
        //     is provided for compatibility with previous versions of Active Server Pages
        //     (ASP).
        //
        // Parameters:
        //   key:
        //     The key (index) of the cookie value.
        //
        // Returns:
        //     The cookie value.
        public string this[string key] { get; set; }
    }

Cookie编程

  浏览器负责管理用户系统上的Cookie,Cookie通过HttpResponse对象发送到浏览器

Response.Cookies["TestOne"].Value = "这是第一种添加Cookie的方式";

HttpCookie cookie = new HttpCookie("TestTwo", "这是第二种添加Cookie的方式");
Response.Cookies.Add(cookie);

多值Cookie

  可以在Cookie中存储一个值,也可以在一个Cookie中存储多个名称/值对。名称/值对称为子键

Response.Cookies["Student"]["FirstName"] = "";
Response.Cookies["Student"]["LastName"] = "";
Response.Cookies["Student"].Expires =DateTime.Now.AddDays(10);

控制Cookie的范围

  默认情况下,一个站点的全部Cookie都将一起存储在客户端上,而且所有Cookie都会随着对该站点发送的任何请求一起发送到服务器。可以通过两种方式设置Cookie的范围:

  1. 将Cookie的范围限制到服务器上的某个文件夹,这允许你将Cookie限制到站点上的某个应用程序
  2. 将范围设置为某个域,这允许你指定域中的哪些子域可以访问Cookie

将Cookie限制到某个文件夹或应用程序

  将Cookie限制到服务器上某个文件夹,需设置Cookie的Path属性

 Response.Cookies["Student"]["FirstName"] = "";
 Response.Cookies["Student"]["LastName"] = "";
 Response.Cookies["Student"].Expires = DateTime.Now.AddDays(10);
 Response.Cookies["Student"].Path = "/Students";

  如果站点名称为www.School.com,则在前面创建的Cookie只能用于路径http://www.School.com/Students的页面及该文件夹下的所有页面。

限制Cookie的域范围

  默认情况下,Cookie与特定域关联。如果站点具有子域,则可以将Cookie于特定的子域关联,若要执行此操作,请设置Cookie的Domain属性。

Response.Cookies["Student"]["FirstName"] = "";
Response.Cookies["Student"]["LastName"] = "";
Response.Cookies["Student"].Expires = DateTime.Now.AddDays(10);
Response.Cookies["Student"].Domain = "support.contoso.com";

读取Cookie

if (Request.Cookies["Student"] != null)
{
HttpCookie cookie
= Request.Cookies["Student"];  string name = Server.HtmlEncode(cookie.Value);
}

读取子键:

if (Request.Cookies["Student"] != null)
{
      string firstName = Server.HtmlEncode(Request.Cookies["Student"]["FirstName"]);
      string lastName = Server.HtmlEncode(Request.Cookies["Student"]["LastName"]);
}

Cookie中的子键被类型化为NameValueCollection类型集合

if (Request.Cookies["Student"] != null)
{
    NameValueCollection collection = Request.Cookies["Student"].Values;
}

修改和删除Cookie

  不能直接修改Cookie,更改Cookie的过程设计创建一个具有新值的新Cookie,然后将其发送到浏览器来覆盖客户端的旧版本Cookie,下面的代码示例演示如何更改存储用户对站点的访问次数的 Cookie 的值:

int counter;
if (Request.Cookies["counter"] == null)
    counter = 0;
else
{
    counter = int.Parse(Request.Cookies["counter"].Value);
}
counter++;

Response.Cookies["counter"].Value = counter.ToString();
Response.Cookies["counter"].Expires = DateTime.Now.AddDays(1);

删除Cookie

  删除 Cookie(即从用户的硬盘中物理移除 Cookie)是修改 Cookie 的一种形式。由于 Cookie 在用户的计算机中,因此无法将其直接移除。但是,可以让浏览器来为您删除 Cookie。该技术是创建一个与要删除的 Cookie 同名的新 Cookie,并将该 Cookie 的到期日期设置为早于当前日期的某个日期。当浏览器检查 Cookie 的到期日期时,浏览器便会丢弃这个现已过期的 Cookie:

 Response.Cookies["Student"]["FirstName"] = "";
 Response.Cookies["Student"]["LastName"] = "";
 Response.Cookies["Student"].Expires = DateTime.Now.AddDays(-10);

删除子Cookie

  若要删除单个子键,可以操作 Cookie 的 Values 集合,该集合用于保存子键。首先通过从 Cookies 对象中获取 Cookie 来重新创建 Cookie。然后您就可以调用 Values 集合的 Remove 方法,将要删除的子键的名称传递给 Remove 方法。接着,将 Cookie 添加到 Cookies 集合,这样 Cookie 便会以修改后的格式发送回浏览器。

原文地址:https://www.cnblogs.com/PerfectSoft/p/2529319.html