博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

NetCore 控制台读取配置文件

Posted on 2018-08-30 11:40  生命如风  阅读(4334)  评论(0编辑  收藏  举报

依赖:

Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Binder
Microsoft.Extensions.Configuration.EnvironmentVariables
Microsoft.Extensions.Configuration.FileExtensions
Microsoft.Extensions.Configuration.Json

读取代码
 var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddEnvironmentVariables();

            IConfigurationRoot configuration = builder.Build();

            ConnectionStrings connectionStrings = new ConnectionStrings();
            configuration.GetSection("ConnectionStrings").Bind(connectionStrings);
appsettings.json
{
  "ConnectionStrings": {
    "SqlServer": "",
    "TiDB": ""
  }
}