You need to enable JavaScript to run this app. 如何为.NET Core控制台应用添加配置文件?
优惠活动
大模型
产品
解决方案
定价
更多

如何为.NET Core控制台应用添加配置文件?

为.NET Core控制台应用添加appsettings.json配置文件的步骤

1. 安装所需NuGet包

先在项目中安装配置相关的官方NuGet包:

  • Microsoft.Extensions.Configuration.Json:提供JSON配置文件的读取支持
  • 可选:Microsoft.Extensions.Configuration.Binder:支持将配置节点绑定到强类型实体
  • 可选:Microsoft.Extensions.DependencyInjection:如果需要通过依赖注入注入配置实例可以安装

可以通过NuGet包管理器搜索安装,或者在项目目录下执行CLI命令:

dotnet add package Microsoft.Extensions.Configuration.Json

2. 添加配置文件并设置属性

  1. 在项目根目录右键新建 → 文本文件,命名为appsettings.json
  2. 填入你的配置内容,示例如下:
{
  "ConnectionStrings": {
    "DefaultDb": "Server=localhost;Database=TestDb;Uid=root;Pwd=123456;"
  },
  "AppSettings": {
    "MaxRetryCount": 3,
    "Timeout": 3000
  }
}
  1. 关键配置:右键appsettings.json → 属性,将「复制到输出目录」选项设置为「如果较新则复制」,避免运行时找不到配置文件。

3. 代码中读取配置

在Program.cs中添加配置加载逻辑,示例代码如下:

using Microsoft.Extensions.Configuration;

// 构建配置实例
var config = new ConfigurationBuilder()
    .SetBasePath(AppContext.BaseDirectory)
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    // 可选:添加不同环境的配置文件,比如开发环境
    // .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT")}.json", optional: true)
    .Build();

// 直接读取配置值
var dbConn = config.GetConnectionString("DefaultDb");
var maxRetry = config.GetValue<int>("AppSettings:MaxRetryCount");
Console.WriteLine($"数据库连接字符串:{dbConn}");
Console.WriteLine($"最大重试次数:{maxRetry}");

// 绑定到强类型实体(需要安装Microsoft.Extensions.Configuration.Binder)
public class AppSettings
{
    public int MaxRetryCount { get; set; }
    public int Timeout { get; set; }
}
var appSettings = config.GetSection("AppSettings").Get<AppSettings>();
Console.WriteLine($"请求超时时间:{appSettings.Timeout}");

如果项目使用依赖注入,还可以将IConfiguration实例注入到容器中,在全局任意位置读取:

using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddSingleton<IConfiguration>(config);
// 注册其他服务
var serviceProvider = services.BuildServiceProvider();

// 后续在服务中构造函数注入IConfiguration即可使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 17:36:05