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

.NET Core 6如何将连接字符串敏感信息移入Secret Manager工具?

解决方案

1. secret.json 中需要添加的内容

打开生成的 secret.json 文件,添加连接字符串的配置项,格式如下:

{
  "ConnectionStrings": {
    "TestDbConnection": "Server=Test; column encryption setting=enabled;Database=Test;user id=User1;password='Password1';Trust Server Certificate=true"
  }
}

2. 修改 DbContext 配置代码

更新你的 OnConfiguring 方法,从配置系统读取机密中的连接字符串,替代硬编码:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .AddUserSecrets<YourDbContextClassName>() // 替换成你的DbContext类名
            .Build();

        optionsBuilder.UseSqlServer(configuration.GetConnectionString("TestDbConnection"));
    }
}

3. 生产服务器部署注意事项

不需要复制 secret.json 到生产服务器。用户机密(User Secrets)是专为本地开发环境设计的,不会被包含在项目发布包中,也绝不应该上传到生产环境。

生产环境的敏感信息(如数据库密码)需通过更安全的方式管理:

  • 配置服务器的环境变量存储连接字符串
  • 使用云服务密钥管理工具(如Azure Key Vault、AWS Secrets Manager)
  • Windows服务器可使用本地计算机机密管理器,Linux服务器可使用环境变量或专用密钥服务

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 15:37:33