您现在的位置是:网站首页> 编程资料编程资料
asp.net各种cookie代码和解析实例_实用技巧_
2023-05-24
333人已围观
简介 asp.net各种cookie代码和解析实例_实用技巧_
Cookie是一段文本信息,在客户端存储 Cookie 是 ASP.NET 的会话状态将请求与会话关联的方法之一。Cookie 也可以直接用于在请求之间保持数据,但数据随后将存储在客户端并随每个请求一起发送到服务器。浏览器对 Cookie 的大小有限制,因此,只有不超过 4096 字节才能保证被接受。
编写Cookie
//方式1:
Response.Cookies["username"].value="mike";
Response.Cookies["username"].Expires=DateTime.MaxValue;
//方式2:
HttpCookie acookie = new HttpCookie("last");
acookie.Value="a";
acookie..Expires=DateTime.MaxValue;
Response.Cookies.Add(acookie);
//方式1:
Response.Cookies["userinfo1"]["name"].value="mike";
Response.Cookies["userinfo1"]["last"].value="a";
Response.Cookies["userinfo1"].Expires=DateTime.MaxValue;
//方式2:
HttpCookie cookie = new HttpCookie("userinfo1");
cookie.Values["name"]="mike";
cookie.Values["last"]="a";
cookie.Expires=DateTime.MaxValue;
//cookie.Expires = System.DateTime.Now.AddDays(1);//设置过期时间 1天
Response.Cookies.Add(cookie);
读取Cookie
Internet Explorer 将站点的 Cookie 保存在文件名格式为
注意:在获取Cookie的值之前,应该确保该 Cookie 确实存在。否则,您将得到一个异常
If (Request.Cookies["userName"]!=null)
{
string str = Request.Cookies("userName").Value;
}
//多值Cookie的读取
If ( Request.Cookies["userInfo1"]!=null )
{
string name=Request.Cookies["userInfo1"]["name"];
string last=Request.Cookies["userInfo1"]["last"];
}
//读取 Cookie 集合
for(int i = 0 ;i
HttpCookie cookies = Request.Cookies;
Response.Write("name="+cookies.Mame+"
");
if (cookies.HasKeys )//是否有子键
{
System.Collections.Specialized.NameValueCollection NameColl
= aCookie.Values ;
for(int j=0;j
Response.Write("子键名="+ NameColl.AllKey[j] +"
");
Response.Write("子键值="+ NameColl[j] +"
");
}
}
else
{
Response.Write("value="+cookies.Value+"
");
}
}
运行此代码时,可看到一个名为“ASP.NET_SessionId”的Cookie,ASP.NET用这个 Cookie 来保存您的会话的唯一标识符。
修改 Cookie
修改的方法与创建方法相同
删除 Cookie
将其有效期设置为过去的某个日期。当浏览器检查 Cookie 的有效期时,就会删除这个已过期的 Cookie。
HttpCookie cookie = new HttpCookie("userinfo1");
cookie.Expires=DateTime.Now.AddDays(-30);
Response.Cookies.Add(cookie);
修改cookie
Response.Cookies["Info"]["user"] = "2";
Response.Cookies["Info"].Expires = DateTime.Now.AddDays(1); //删除cookie下的属性
HttpCookie acookie=Request.Cookies["Info"];
acookie.Values.Remove("userid");
acookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(acookie); //删除所有cookie,就是设置过期时间为现在就行了
int limit=Request.Cookies.Count - 1;
for(int i=0;i
acookie = Request.Cookies(i)
acookie.Expires = DateTime.Now.AddDays(-1)
Response.Cookies.Add(acookie)
}
如果有主站及二级域名站且cookie要共享的话则要加入如下设置
cookie.Domain = ".主域名";//例如.keleyi.com
cookie.Path = "/";
Cookie.Expires AddDays(-1)是立即过期
相关内容
- asp.net上传execl文件后,在页面上加载显示(示例代码)_实用技巧_
- asp.net(C#)生成Code39条形码实例 条码枪可以扫描出_实用技巧_
- EasyUI Tree+Asp.net实现权限树或目录树导航的简单实例_实用技巧_
- 获取DataRow[]的值示例_实用技巧_
- asp.net页面中时间格式化的示例_实用技巧_
- subsonic3.0插件更新字符串过长引发的异常修复方法_实用技巧_
- Asp.net response对象与request对象使用介绍_实用技巧_
- asp.net 使用js分页实现异步加载数据_实用技巧_
- .NET Web开发之.NET MVC框架介绍_实用技巧_
- 记录asp.net网站是什么原因导致停止运行的代码_实用技巧_
