asp.net 关于cookie的操作
一、无子键或单级cookie 读写
(1)、写入:
第一种
HttpCookie cookie=new HttpCookie("User");
cookie.Value="admin";
cookie.Expires=DateTime.Now.AddMinutes(1000);
HttpContext.Current.Response.AppendCookie(cookie);
或者
HttpContext.Current.Response.Cookies.Add(cookie);
第二种:
HttpContext.Current.Response.Cookies['User'].Value="admin";
HtttpContext.Current.Response.Cookies["User"].Exipres=DateTime.Now.AddMinutes(100);
(2)、读取
if(HttpContext.Current.Request.Cookies[key]!=null)
{
string value=HttpContext.Current.Request.Cookies[key];
}
else
{
string value="不存在"+key;
}
(3)、修改
if(HttpContext.Current.Request.Cookies[key]!=null)
{
HttpCookie cookie=HttpCookie.Current.Request.Cookies[key];
cookie.Value=value;
HttpContext.Current.Response.Cookies.Add(cookie);
}
(4)、删除
if(HttpContext.Current.Request.Cookies[key]!=null)
{
HttpCookie cookie=HttpContext.Current.Request.Cookies[key];
cookie.Expires=DateTime.Now.AddMiuntes(time);//负数
HttpContext.Current.Response.Cookies.Add(cookie);
}
二、有子键或多级cookie 读写
(1)、创建
HttpCookie cookie=new HttpCookie("user","admin");
或者
HttpCookie cookie=new HttpCookie("user");
cookie.Value="admin";
-------------------------------
cookie.Expires=DateTime.Now.AddMinutes(2);
cookie.Values["Name"]="Li";
或
cookie.Values.Add("Phone","12300000");
---------------------------------
HttpContext.Current.Response.Cookies.Add(cookie);
(2)、读取
if(HttpContext.Current.Request.Cookies[key]!=null)
{
string value=HttpContext.Current.Request.Cookies[key][subkey] ?? "不存在:"+key+"->"+subkey;
}
else
{
string value="不存在"+key;
}
(3)、修改
if(HttpContext.Current.Request.Cookies[key]!=null)
{
HttpCookie cookie=HttpCookie.Current.Request.Cookies[key];
cookie[subkey].Value=value;
HttpContext.Current.Response.Cookies.Add(cookie);
}
本文作者:小魔鬼coder
本文链接:https://www.cnblogs.com/coderblog/p/9067577.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 探秘 MySQL 索引底层原理,解锁数据库优化的关键密码(下)
· 大模型 Token 究竟是啥:图解大模型Token
· 35岁程序员的中年求职记:四次碰壁后的深度反思
· 继承的思维:从思维模式到架构设计的深度解析
· 如何在 .NET 中 使用 ANTLR4
· 2025,回顾出走的 10 年
· 【保姆级教程】windows 安装 docker 全流程
· 分享 3 款基于 .NET 开源且免费的远程桌面工具
· 基于Docker+DeepSeek+Dify :搭建企业级本地私有化知识库超详细教程
· 由 MCP 官方推出的 C# SDK,使 .NET 应用程序、服务和库能够快速实现与 MCP 客户端