如何为.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. 添加配置文件并设置属性
- 在项目根目录右键新建 → 文本文件,命名为
appsettings.json - 填入你的配置内容,示例如下:
{ "ConnectionStrings": { "DefaultDb": "Server=localhost;Database=TestDb;Uid=root;Pwd=123456;" }, "AppSettings": { "MaxRetryCount": 3, "Timeout": 3000 } }
- 关键配置:右键
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
相关产品推荐
相关产品推荐

