最经在使用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/archive/2012/05/31/2529319.html

ASP.NET Cookie相关推荐

  1. ASP.Net Cookie(几个不同出处)

    Cookie的用法也和ASP中差不多.比如我们建立一个名为aspcn,值为飞刀的cookie HttpCookie cookie = new HttpCookie["aspcn"] ...

  2. [转]PHP或ASP   中Cookie禁用了,Session还能用吗?

    http://laiguowei2004.blog.163.com/blog/static/3682900020107302248722/ COOKIE和SESSION本身是两码事,只是COOKIE可 ...

  3. Asp之Cookie篇—概述Cookie原理、归纳Cookie方法属性及应用

    什么是Cookies? Cookies是数据包,可以让网页具有记忆功能,在某台电脑上记忆一定的信息.Cookies的工作原理是,第一次由服务器端写入到客户端的系统中.以后每次访问这个网页,都是先由客户 ...

  4. asp.Net Cookie demo

    代码 1 //写入 2   protected void Button2_Click(object sender, EventArgs e) 3 { 4 HttpCookie cookie=new H ...

  5. asp.net cookie操作-添加cookie,添加键值,移除cookie,移除键值

    1 public class Cookies 2 { 3 /// <summary> 4 /// 添加cookie 5 /// </summary> 6 /// <par ...

  6. Asp.net Cookie使用与简介

    什么是Cookie 一段文本数据,默认存储在客户端,一种存放在浏览器缓存,一种存放在磁盘,最大可存储4kb. 一个客户端状态保持机制,(网站的数据是存在客户端),与隐藏域ViewState对象都属于这 ...

  7. asp.net 中 SESSION和COOKIE的使用

    在各个网页间的变量传递和一些记录用户的登陆信息要用到SESSION和COOKIE.在ASP.NET中使用COOKIE比ASP中稍微麻烦一点,因为我们要申明变量. 首先看一下SESSION的使用,基本和 ...

  8. cookie 操作详解 (asp.net javascript)

    (1)ASP.NET cookie 操作详解|cookie 写入.读取.修改.删除2008年10月18日     //写入     protected void Button2_Click(objec ...

  9. ASP.Net ViewState的实现

    选择自 timmy3310 的 Blog ViewState是.Net中提出的状态保存的一种新途径(实际上也是老瓶装新酒):我们知道,传统的Web程序保存状态的方式有这样几种:   1.Applica ...

最新文章

  1. 基于深度学习的可疑活动视频分析
  2. win7安装MongoDB学习笔记
  3. python时间序列因果检验_用python做时间序列预测八:Granger causality test(格兰杰因果检验)...
  4. mysql执行出错:Table 'k_user' is read only
  5. internal error:failed to get path of 64-bit Program Files directory
  6. Linux 命令(15)—— umask 命令(builtin)
  7. 一个女算法程序媛的日常
  8. 【数学基础】机器学习中的几个熵
  9. adm怎么下bt连接_迅雷不能下载版权敏感资源,试试这两款优秀的BT下载神器
  10. 计算机科学美国大学专业,最新!2019年USNews美国大学计算机专业排名
  11. 利用 IP 扩展访问列表实现应用服务的访问限制
  12. linux中mtd是什么目录,Linux mtd system
  13. Comparing the Effects of DNS, DoT, and DoH
  14. aspose pdf java,Java 使用aspose.pdf将多张图片转成pdf的方法及示例代码
  15. 自己动手搞个印象笔记桌面版
  16. 前端分享之tinymce编辑器设置默认字体
  17. 【全方面预防U盘病毒侵入】
  18. nn.CrossEntropyLoss (内置了Softmax) 不要再用softmax
  19. Pandas读书笔记
  20. 银联银行卡交换系统8583报文解析

热门文章

  1. 完成工作表-使用Google Spreadsheets作为数据后端
  2. 手动部署OpenStack环境(三:OpenStack环境预配置)
  3. 三菱fx2n64mr说明书_三菱FX2N可编程控制器使用手册
  4. java递归排雷_C语言实现扫雷小游戏
  5. java 多维数组转化为字符串
  6. py 的 第 31 天
  7. 5.1 python的缩进
  8. Samba amp; Nginx - Resource temporarily unavailable
  9. 转载:python原生态的输入窗口抖动+输入特效
  10. 使用Depth Texture