.NET 网站报错:Error unprotecting the session cookie. 解决方法

在.NET网站的日志里看到如下报错:Error unprotecting the session cookie. Exception: System.Security.Cryptography.CryptographicException: The key {1cec9363-208e-4f35-83fb-8d08dec50c78} was not found in the key ring. For more information go to https://aka.ms/aspnet/dataprotectionwarning at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status) at Microsoft.AspNetCore.Session.CookieProtection.Unprotect(IDataProtector protector, String protectedText, ILogger logger)。

这个问题的核心是:ASP.NET Core 会用 Data Protection 系统来加密 Session Cookie,其中包含一个 key-id(GUID)指向当前的加密密钥。如果你重启应用程序、换了环境(例如发布、部署、容器重启),或密钥没有被持久化保存并共享,旧 Cookie 存在但对应密钥不在 key‑ring 里,访问时就会发生 CryptographicException: The key {...} was not found in the key ring 错误。

报错常见原因

1. 旧的浏览器 Cookie:浏览器保留了之前的 Session Cookie,但当前应用没保留对应密钥,直接解密失败。可以在新标签页(隐身模式)中打开,或清除 Cookie 即可解决。

2. 无持久化密钥存储:

  • 本地应用在 Windows 上默认将密钥存到注册表或 %LOCALAPPDATA%\ASP.NET\DataProtection-Keys\ 文件夹里。Linux 容器中默认仅保存在内存中,重启就丢失。
  • 多实例部署(如 Kubernetes、负载均衡、Azure Slot Swap)如果没共享 key 存储,各实例使用的 key‑ring 不一致,交换后也会发生找不到 key 的情况。

解决方法

清浏览器 cookie 或在隐身窗口打开,直接的快速修复方式。

多实例/容器/生产环境,将 Data Protection 密钥持久化并共享。

评论