【问题标题】:Dotnet Core 3.1: How to use AddJsonFile with absolute path to file?Dotnet Core 3.1:如何将 AddJsonFile 与文件的绝对路径一起使用?
【发布时间】:2020-11-20 00:23:00
【问题描述】:

我有一个 dotnet 应用程序,我需要从两个相对路径(常规 appsettings.Jsonappsettings.Development.json)以及绝对路径 /config/appsettings.json 中提取配置。我找不到办法做到这一点。从the docs,路径arg 是Path relative to the base path stored in Properties of builder. 如何设置它以从绝对路径/config/filename.json 读取配置?

动机: 我正在对 dotnet 应用程序进行 docker 化,因此我计划保留不会通常在常规 publish/appsettings.json 中的部署之间更改的配置,并在 /config/appsettings.json 中部署特定配置(这是我'将在部署时挂载到容器上)。

【问题讨论】:

标签: c# .net asp.net-web-api .net-core


【解决方案1】:

您可以像这样编辑CreateHostBuilder 方法:

public static IHostBuilder CreateHostBuilder(string[] args)
{
    var builder = Host.CreateDefaultBuilder(args);
    builder.ConfigureAppConfiguration(cfgBuilder =>
       {
           var provider = new PhysicalFileProvider("/config"); // Create a dedicated FileProvider based on the /config directory
           cfgBuilder.AddJsonFile(provider, "filename.json", true, true); // Add the filename.json configuration file stored in the /config directory
       });
    builder.ConfigureWebHostDefaults(webBuilder =>
       {
            webBuilder.UseStartup<Startup>();
       });

    return builder;
}

【讨论】:

  • 还没有真正尝试过,但很确定它会起作用。谢谢!
【解决方案2】:

agnivesh 试试这个 sn-p 代码示例:

        public static class AppConfigurations
        {
            private static IConfigurationRoot BuildConfiguration(this IWebHostEnvironment env)
            {
                var builder = new ConfigurationBuilder()
                    .SetBasePath(env.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                    .AddJsonFile("config/appsettings.json", optional: true, reloadOnChange: true);
                //
                //  TODO
                //
                return builder.Build();
            }
        }

现在在 Startup 类构造器中调用这个类函数:

public Startup(IWebHostEnvironment env)
    {
        _appConfiguration = env.BuildConfiguration();
    }

【讨论】:

  • 我正在使用 DefaultWebHostBuilder。无法控制整个配置。另外,我认为config/appsettings.json 会寻找 {contentrootpath}/config/appsettings.json
【解决方案3】:

我使用了一个技巧..“相对路径”,但是父级...可以使用“../”

【讨论】:

    猜你喜欢
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 2020-07-14
    • 2021-01-09
    • 2021-10-18
    相关资源
    最近更新 更多