appsettings.json 默认不会自动加载,需显式构建 IConfiguration 实例并注册;控制台或类库项目必须手动调用 ConfigurationBuilder.AddJsonFile;读取嵌套对象须用 GetSection().Get(),而非 GetValue();环境配置文件需手动指定且大小写敏感。
appsettings.json 默认不被 C# 项目自动加载
新建的 .NET Core 或 .NET 5+ 项目默认会包含 appsettings.json,但它不会“自动生效”——你得显式构建 IConfiguration 实例并注册它。控制台、类库、甚至某些 ASP.NET Core 模块(如中间件外的静态方法)里直接用 Configuration["Key"] 会返回 null,因为没初始化配置源。
常见错误现象:Configuration.GetSection("Logging").GetChildren() 返回空集合;Configuration.GetValue("Timeout") 始终是 0;读取不到自定义节内容。
- ASP.NET Core Web 项目:通常在
Program.cs中通过WebApplication.CreateBuilder(args)自动完成配置加载,无需手动干预 - 控制台或类库项目:必须自己调用
ConfigurationBuilder并添加.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) -
reloadOnChange: true仅在文件系统支持热重载的环境(如开发时的 Kestrel + dotnet watch)下有效,发布后不生效
读取嵌套对象需用 Get() 而非 GetValue()
GetValue() 只适用于扁平键(如 "ConnectionStrings:Default"),遇到对象结构(如 "Features:EnableCache" 或整个 "Features" 节)必须用 GetSection().Get(),否则返回默认值或抛异常。
例如,有如下 JSON:
{
"Features": {
"EnableCache": true,
"MaxRetries": 3
}
}
正确做法:
- 读布尔值:
config.GetSection("Features").GetValue("EnableCache") - 读整个对象:
config.GetSection("Features").Get(),其中FeaturesOptions是含public bool EnableCache { get; set; }和public int MaxRetries { get; set; }的类 - 错误写法:
config.GetValue("Features")—— 这会失败,因为GetValue不支持反序列化对象
环境配置文件(appsettings.Development.json)需手动指定环境名
appsettings.{Environment}.json 不会自动加载,除非你在 ConfigurationBuilder 中明确调用 .AddJsonFile($"appsettings.{env}.json", optional: true),且 env 值必须与当前运行时环境匹配。