zoukankan      html  css  js  c++  java
  • 如何在.Net Core 2.0 App中读取appsettings.json

    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.

    原文链接

  • 相关阅读:
    Html代码查看器
    Http请求
    HTTP协议
    AsyncTask2
    AsyncTask
    幽灵线程解决方案
    handler消息机制入门
    多叉树的树形背包常见建模方法
    Codeforces Round #263
    怎样在win7下装ubuntu(硬盘版安装)
  • 原文地址:https://www.cnblogs.com/OpenCoder/p/9761067.html
Copyright © 2011-2022 走看看