首页 > 移动平台 > 详细

如何在.Net Core 2.0 App中读取appsettings.json

时间:2018-10-09 16:34:48      阅读:237      评论:0      收藏:0      [点我收藏+]

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"));
    Console.WriteLine(configuration.GetSection("ConnectionStrings:Storage").Value);
}

 

In the case of receiving the error “IConfigurationBuilder does not contain a definition for AddJsonFile” just rebuild the project and close and re-open Visual Studio.

 

原文链接

 

如何在.Net Core 2.0 App中读取appsettings.json

原文:https://www.cnblogs.com/OpenCoder/p/9761067.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!