惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

MyScale Blog
MyScale Blog
博客园 - 司徒正美
A
About on SuperTechFans
Vercel News
Vercel News
H
Hackread – Cybersecurity News, Data Breaches, AI and More
爱范儿
爱范儿
I
InfoQ
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园_首页
Google DeepMind News
Google DeepMind News
T
Tailwind CSS Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
F
Fortinet All Blogs
S
SegmentFault 最新的问题
阮一峰的网络日志
阮一峰的网络日志
D
Docker
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
G
Google Developers Blog
Stack Overflow Blog
Stack Overflow Blog
M
MIT News - Artificial intelligence
Jina AI
Jina AI
H
Help Net Security
量子位
IT之家
IT之家

博客园 - JasonBie

使用NPOI编辑Excel C# datagridview 快速导出数据到Excel Outlook2016 不能自动配置企业Exchange的解决办法 Linq实现left join左连接 电脑端微信语音像机器人解决办法 解决sql server collation conflict Asp.net APP 重置密码的方式 jQuery dataTables 列不对齐的原因 JavaScript 获得客户端IP Entity Framework Linq 动态组合where条件 查询SQLSERVER执行过的SQL记录 Asp.net Web API 返回Json对象的两种方式 Read Excel file from C# JavaScript测试工具比较: QUnit, Jasmine, and Mocha Asp.net Form验证后造成URL参数重复的问题 MVC删除数据的方法 Session State Transferring Information Between Pages View State
Cookie
JasonBie · 2012-04-12 · via 博客园 - JasonBie

Before you can use cookies, you should import the System.Net namespace so you can easily work with the appropriate types: 

Cookies are fairly easy to use. Both the Request and Response objects (which are provided through Page properties) provide a Cookies collection. The important trick to remember is that you retrieve cookies from the Request object, and you set cookies using the Response object. 

To set a cookie, just create a new HttpCookie object. You can then fill it with string information (using the familiar dictionary pattern) and  attach it to the current web response: 

// Create the cookie object. 
HttpCookie cookie = new HttpCookie("Preferences"); 
 
// Set a value in it. 
cookie["LanguagePref"] = "English"
 
// Add another value. 
cookie["Country"] = "US"
 
// Add it to the current web response. 
Response.Cookies.Add(cookie); 

A cookie added in this way will persist until the user closes the browser and will be sent with every request. To create a longer-lived cookie, you can set an expiration date: 

// This cookie lives for one year. 
cookie.Expires = DateTime.Now.AddYears(1); 

You retrieve cookies by cookie name using the Request.Cookies collection: 

HttpCookie cookie = Request.Cookies["Preferences"]; 
 
// Check to see whether a cookie was found with this name. 
// This is a good precaution to take, 
// because the user could disable cookies, 
// in which case the cookie will not exist. 
string language; 
if (cookie != null

    language = cookie["LanguagePref"]; 

The only way to remove a cookie is by replacing it  with a cookie that has an expiration date that has already passed. This code demonstrates the technique: 

HttpCookie cookie = new HttpCookie("Preferences"); 
cookie.Expires = DateTime.Now.AddDays(-1); 
Response.Cookies.Add(cookie);