【问题标题】:how to get custom environment variables in IConfiguration in .NET Core如何在 .NET Core 的 IConfiguration 中获取自定义环境变量
【发布时间】:2019-02-25 04:54:27
【问题描述】:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
    .ConfigureAppConfiguration(a => { 
        a.AddEnvironmentVariables();
    })
    .UseStartup<Startup>();

在我这样调用的 API 内部,它不支持自定义变量,我如何获取自定义变量 我已经在系统中创建了一个自定义变量。

public ActionResult<IEnumerable<string>> Get() {
    var t = configuration.GetSection("yash2").Value;
    return new string[] { "value1", "value2" };
}

【问题讨论】:

    标签: .net .net-core


    【解决方案1】:

    我之前给出了错误的答案。谢谢詹姆斯指出这一点。

    要将环境变量加载到应用程序中,您需要使用 __ 分隔符来存储变量。

    yesh2__config1="config1Value"
    yesh2__config2="config2Value"
    

    那么这里就可以使用了。

    configuration.GetSection("yash2")
    

    您可以传递要加载的键,而不是加载所有环境变量。

     a.AddEnvironmentVariables("yesh2");
    

    【讨论】:

    • 我相信他问的是引入系统环境变量,而不是使用 appsettings.json 文件。要从环境变量中引入一个部分,环境变量需要类似于“yash2__BaseUrl”并设置为“value1”。 configuration.GetSection("yash2") 将返回一个配置部分,其中包含前缀为 yash2__ 的所有环境变量。
    猜你喜欢
    • 2016-02-17
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    • 2017-12-04
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多