gpt4 book ai didi

c# - .NET Core 中的环境变量配置

转载 作者:行者123 更新时间:2023-12-03 16:41:15 24 4
gpt4 key购买 nike

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

  • 我需要有两个级别的配置:appsettings.json和环境变量。
  • 我想用 DI对于我的配置,通过 IOptions .
  • 我需要环境变量来覆盖 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:ElasticSearchUrl , ElasticSearchUrl ,甚至尝试将前缀指定为 .AddEnvironmentVariables("ConnectionStrings")没有任何结果。

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

    最佳答案

    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

    关于c# - .NET Core 中的环境变量配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46038549/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com