C# 配置文件读取方法 C#如何读取appsettings.json

来源:这里教程网 时间:2026-02-21 17:41:17 作者:

appsettings.json 默认不被 C# 项目自动加载

新建的 .NET Core 或 .NET 5+ 项目默认会包含

appsettings.json
,但它不会“自动生效”——你得显式构建
IConfiguration
实例并注册它。控制台、类库、甚至某些 ASP.NET Core 模块(如中间件外的静态方法)里直接用
Configuration["Key"]
会返回
null
,因为没初始化配置源。

常见错误现象:

Configuration.GetSection("Logging").GetChildren()
返回空集合;
Configuration.GetValue<int>("Timeout")</int>
始终是 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<t>()</t>
只适用于扁平键(如
"ConnectionStrings:Default"
),遇到对象结构(如
"Features:EnableCache"
或整个
"Features"
节)必须用
GetSection().Get<t>()</t>
,否则返回默认值或抛异常。

例如,有如下 JSON:

{
  "Features": {
    "EnableCache": true,
    "MaxRetries": 3
  }
}

正确做法:

读布尔值:
config.GetSection("Features").GetValue<bool>("EnableCache")</bool>
读整个对象:
config.GetSection("Features").Get<featuresoptions>()</featuresoptions>
,其中
FeaturesOptions
是含
public bool EnableCache { get; set; }
public int MaxRetries { get; set; }
的类
错误写法:
config.GetValue<featuresoptions>("Features")</featuresoptions>
—— 这会失败,因为
GetValue
不支持反序列化对象

环境配置文件(appsettings.Development.json)需手动指定环境名

appsettings.{Environment}.json
不会自动加载,除非你在
ConfigurationBuilder
中明确调用
.AddJsonFile($"appsettings.{env}.json", optional: true)
,且
env
值必须与当前运行时环境匹配。

ASP.NET Core 项目中,

IWebHostEnvironment.EnvironmentName
IHostEnvironment.EnvironmentName
决定加载哪个文件;但纯控制台程序没有内置环境变量,你得自己设置:

方式一:设置环境变量
DOTNET_ENVIRONMENT=Development
(Windows 下用
set DOTNET_ENVIRONMENT=Development
方式二:代码中传入:
var env = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production";
,再拼接文件名
注意:
optional: true
很关键——否则缺失
appsettings.Development.json
时会抛
FileNotFoundException

配置键名大小写敏感,但 JSON 文件本身不区分

JSON 解析器不关心大小写,但 .NET 的

IConfiguration
键是**大小写敏感**的。如果你在 JSON 中写
"connectionstrings"
,而代码里读
Configuration.GetConnectionString("ConnectionStrings:Default")
,就会返回
null

常见陷阱:

GetConnectionString()
方法内部会查找
"ConnectionStrings"
(首字母大写)节,所以 JSON 中必须是
"ConnectionStrings": { ... }
,不能是
"connectionstrings"
自定义节名建议统一 PascalCase,避免混用
ApiSettings
apiSettings
调试时可用
config.AsEnumerable()
查看所有实际加载的键名,确认大小写是否一致

配置加载不是“放个 JSON 就能用”的事,最常出问题的地方其实是路径没设对、环境名没传进去、或者误用

GetValue
去反序列化对象。动手前先确认
IConfiguration
实例是否真的包含了你要的键。

相关推荐