您的位置:首页 > 移动开发

Adding appsettings.json to a .NET Core console app

2018-07-17 15:31 501 查看

This is something that strangely doesn’t seem to be that well documented and took me a while to figure out though in the end it’s pretty simple.

All that’s required is to add the following NuGet packages and an appsettings.json file.

  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Configuration.FileExtensions
  • Microsoft.Extensions.Configuration.Json

The appsettings.json files “Copy to Output Directory” property should also be set to “Copy if newer” so that the application is able to access it when published.

The settings are injected in the main method rather than in the startup method as with web apps but the code is essentially the same.

static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

IConfigurationRoot configuration = builder.Build();

Console.WriteLine(configuration.GetConnectionString("Storage"));
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐