.NET Core 环境变量配置

Environment variables configuration in .NET Core

我在我的 API 中使用 .NET Core 1.1,但遇到了一个问题:

  1. 我需要两级配置:appsettings.json和环境变量。
  2. 我想通过 IOptions 为我的配置使用 DI
  3. 我需要环境变量来覆盖 appsettings.json 值。

到目前为止我都是这样做的:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddEnvironmentVariables();
}

public IServiceProvider ConfigureServices(IServiceCollection services)
{
     // Something here
     services.Configure<ConnectionConfiguration>(options =>
            Configuration.GetSection("ConnectionStrings").Bind(options));
     // Something there
}

我的appsettings.json是这样组成的

{
    "ConnectionStrings": {
        "ElasticSearchUrl": "http://localhost:4200",
        "ElasticSearchIndexName": "myindex",
        "PgSqlConnectionString": "blablabla"
    }
}

我将所有配置映射到我的 class ConnectionConfiguration.cs。但是我也无法映射环境变量。我尝试了像这样的名称:ConnectionStrings:ElasticSearchUrlElasticSearchUrl,甚至尝试将前缀指定为 .AddEnvironmentVariables("ConnectionStrings"),但没有任何结果。

我应该如何命名环境变量以便它可以映射到 services.Configure<TConfiguration>()

我相信您正在寻找这个:

var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        this.Configuration = builder.Build();

我有 3 个配置

  1. 开发最终版
  2. 本地开发
  3. 开发测试

还有4个*.json个文件

  • appsettings.json
  • appsettnigs.dev-final.json
  • appsettings.dev-local.json
  • appsettings.dev-test.json

appsettings.json 保存全局配置值,其他文件保存特定值。

看看ASP.NET Core Configuration with Environment Variables in IIS

To do the same with environment variables, you just separate the levels with a colon (:), such as HitchhikersGuideToTheGalaxy:MeaningOfLife.

在您的情况下,您将使用问题中提到的 ConnectionStrings:ElasticSearchUrl

另请注意以下事项:

When you deploy to IIS, however, things get a little trickier, and unfortunately the documentation on using configuration with IIS is lacking. You go into your server's system settings and configure all your environment variables. Then, you deploy your app to IIS, and it... explodes, because it's missing those necessary settings.

Turns out, in order to use environment variables with IIS, you need to edit the advanced settings for your App Pool. There, you'll find a setting called "Load User Profile". Set that to True. Then, recycle the App Pool to load in the environment variables. Note: you must do this even if your environment variables are added as "System variables", rather than "User variables".

The : separator doesn't work with environment variable hierarchical keys on all platforms. __, the double underscore, is supported by all platforms and it is automatically replaced by a :

尝试像这样命名环境变量ConnectionStrings__ElasticSearchUrl

Source