首页 > 解决方案 > asp.net core 2.0 特定版本 appsettings

问题描述

我正在将 apt.net core 2.0 web api 部署为 Windows 服务。我的每个环境都有一个 appsettings 文件(例如:appsettings.Development.json)。

但是,我的环境特定 appsetting 文件未加载到我的配置中。这是代码:

        var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
        var pathToContentRoot = Path.GetDirectoryName(pathToExe);       

        return WebHost.CreateDefaultBuilder(args)
                .UseContentRoot(pathToContentRoot)
                .ConfigureAppConfiguration((builderContext, config) =>
                {
                    IHostingEnvironment env = builderContext.HostingEnvironment;

                    config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                        .AddJsonFile("appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
                        //.AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true)

                })
                .UseStartup<Startup>()
               .UseUrls(myUrl)              
               .Build();

我试图通过硬编码(注释中的代码)值来加载特定于环境的配置文件,这是有效的。我还可以保证我的环境名称和文件名之间没有拼写错误。

我的环境名称是通过 dployment 机器上的环境变量设置的。

标签: asp.net-core-2.0

解决方案


第二个 .addJson 应该是

.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

您在字符串之前缺少 $


推荐阅读