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

.NET8 API无法读取自定义secrets.json配置文件问题排查

.NET8 API自定义secrets.json配置读取为null问题排查

问题场景

在.NET8 API项目中,添加了自定义secrets.json文件存储敏感配置,标准appsettings.json的配置可正常读取,但secrets.json中目标配置段始终返回null。

相关代码与配置

Program.cs

var env = ConfigHelpers.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var config = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env}.json", optional: true, reloadOnChange: true)
                .AddJsonFile("secrets.json", optional: false, reloadOnChange: true)
                .AddEnvironmentVariables()
                .AddCommandLine(args)
                .Build();

var configurationModel = config.GetSection(ConfigurationModel.SectionName).Get<ConfigurationModel>();
builder.Services.AddSingleton(configurationModel);

var secretsConfigurationModel = config.GetSection(SecretsConfigModel.SectionName).Get<SecretsConfigModel>();
builder.Services.AddSingleton(secretsConfigurationModel);

读取appsettings的模型类

public class ConfigurationModel
{
    public const string SectionName = "AppConfig";
    public int SaverDelay { get; set; } = 10000;
    public int SaverBatchSize { get; set; } = 1000;
}

读取secrets的模型类

public class SecretsConfigModel
{
    public const string SectionName = "Encryption";
    public string TokenSecretSalt { get; set; }
}

原secrets.json配置

{
  "Encryption": [
    { "TokenSecretSalt": "c48mt45ty487tg47y85mh8g5h6587h6g586gh568756" }
  ]
}

错误原因

secrets.json中的"Encryption"字段被定义为数组([]包裹),但SecretsConfigModel是单一对象类型,.NET配置系统无法将数组结构映射到非集合类的对象,因此Get<SecretsConfigModel>()返回null。

修复方案

方案1:修改secrets.json结构(推荐)

将Encryption的数组结构改为单一对象,匹配SecretsConfigModel的类型:

{
  "Encryption": {
    "TokenSecretSalt": "c48mt45ty487tg47y85mh8g5h6587h6g586gh568756"
  }
}

方案2:检查文件属性

确保secrets.json的复制到输出目录属性设置为如果较新则复制或始终复制,避免程序运行时无法找到该文件导致读取失败。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 20:15:04