You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 6中加密Cookie遇System.Security引用问题求解决方案

ASP.NET Core 6 中Cookie加密解密的替代方案

MachineKey是ASP.NET Framework专属的API,在ASP.NET Core 6中已被废弃,无法通过System.Security引用使用。你需要改用官方推荐的DataProtection API来实现Cookie的加密解密,具体操作如下:

1. 注册DataProtection服务

在Program.cs中完成DataProtection服务的注册,可按需配置密钥持久化(避免应用重启后无法解密历史加密数据):

var builder = WebApplication.CreateBuilder(args);

// 注册DataProtection服务
builder.Services.AddDataProtection()
    .SetApplicationName("YourApplicationName") // 隔离不同应用的密钥空间
    .PersistKeysToFileSystem(new DirectoryInfo(@"C:\YourKeyStoragePath")); // 可选:将密钥持久化到文件系统

// 其他服务注册...

var app = builder.Build();

// 中间件配置...

app.Run();

2. 注入并使用IDataProtector

在需要处理Cookie加密的类(如控制器、业务服务)中,通过构造函数注入IDataProtectionProvider,创建专用保护器后执行加密解密操作:

using Microsoft.AspNetCore.DataProtection;

public class CookieHandlerController : Controller
{
    private readonly IDataProtector _cookieProtector;

    public CookieHandlerController(IDataProtectionProvider dataProtectionProvider)
    {
        // 创建指定用途的保护器,用途字符串需与加密解密保持一致
        _cookieProtector = dataProtectionProvider.CreateProtector("ProtectCookie");
    }

    // 设置加密Cookie
    public IActionResult SetEncryptedCookie()
    {
        string cookieContent = "Text for Cookie";
        // 加密内容
        string encryptedValue = _cookieProtector.Protect(cookieContent);
        // 添加到响应Cookie
        Response.Cookies.Append("EncryptedCookie", encryptedValue);
        return Ok();
    }

    // 获取并解密Cookie
    public IActionResult GetDecryptedCookie()
    {
        if (Request.Cookies.TryGetValue("EncryptedCookie", out string encryptedValue))
        {
            // 解密内容
            string decryptedContent = _cookieProtector.Unprotect(encryptedValue);
            return Ok(decryptedContent);
        }
        return NotFound("Cookie not found");
    }
}

关键说明

  • 用途字符串:CreateProtector传入的字符串(如"ProtectCookie")用于隔离不同加密场景,确保只有相同用途的保护器才能解密对应内容,提升安全性。
  • 密钥持久化:生产环境必须配置密钥持久化(如文件系统、Azure Key Vault),默认开发环境密钥存储在内存中,应用重启后会丢失密钥,导致历史加密数据无法解密。
  • 依赖说明:ASP.NET Core项目默认已包含Microsoft.AspNetCore.DataProtection包,无需额外安装。

内容的提问来源于stack exchange,提问作者RezaShirazSarhad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 08:30:41