Cookie练习
<asp:Button ID="Button1" runat="server" Text="写入Cookie" OnClick="Button1_Click" /> <asp:Button ID="Button3" runat="server" Text="读出Cookie" OnClick="Button3_Click" /> <asp:Button ID="Button2" runat="server" Text="删除Cookie" OnClick="Button2_Click" />
后台代码:
protected void Button1_Click(object sender, EventArgs e) {
//特殊加密算法 HttpCookie cookie = new HttpCookie("name"); cookie.Value = Encode("shang", "Rainight"); cookie.Expires = DateTime.Now.AddDays(1); HttpContext.Current.Response.Cookies.Add(cookie); Response.Write("写入成功"); }
protected void Button2_Click(object sender, EventArgs e) { HttpCookie cookie = new HttpCookie("name"); cookie.Expires = DateTime.Now.AddDays(-1); HttpContext.Current.Response.Cookies.Add(cookie);
}
protected void Button3_Click(object sender, EventArgs e) {
if (Request.Cookies["name"] != null) { Response.Write(Decode(Request.Cookies["name"].Value, "Rainight")); } else { Response.Write("您还没有写入值!"); } }
//加密 public static string Encode(string str, string key) { try { DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8)); provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8)); byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(str); MemoryStream stream = new MemoryStream(); CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write); stream2.Write(bytes, 0, bytes.Length); stream2.FlushFinalBlock(); StringBuilder builder = new StringBuilder(); foreach (byte num in stream.ToArray()) { builder.AppendFormat("{0:X2}", num); } stream.Close(); return builder.ToString(); } catch { return "不是用Encrypt加密的字符串,加密失败!"; } } //解密 public static string Decode(string str, string key) { try { DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8)); provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8)); byte[] buffer = new byte[str.Length / 2]; for (int i = 0; i < (str.Length / 2); i++) { int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10); buffer[i] = (byte)num2; } MemoryStream stream = new MemoryStream(); CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write); stream2.Write(buffer, 0, buffer.Length); stream2.FlushFinalBlock(); stream.Close(); return Encoding.GetEncoding("GB2312").GetString(stream.ToArray()); } catch { return "不是用Encrypt加密的字符串,解密失败!"; }
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构