.net core 环境变量配置提供程序 电脑版发表于:2020/6/22 11:00 ![.netcore](https://img.tnblog.net/arcimg/hb/c857299a86d84ee7b26d181a31e58234.jpg ".netcore") >#.net core 环境变量配置提供程序 [TOC] <br/> 适用场景 ------------ <br/> - 在 **Docker** 中运行时 - 在 **k8s** 中运行时 - 需要设置 **Asp.net Core** 的一些内置特殊配置时 <br/> 特性 ------------ <br/> - 对于配置分层键,支持用双下横线 "_" 代替 "." - 支持根据前缀加载 <br/> 简单运用示例 ------------ <br/> >###项目结构 ![项目结构](https://img.tnblog.net/arcimg/hb/03b2abdcadf14464b58aba2a4de50dab.png) >###添加内容 <br/> >添加环境变量 ![添加环境变量](https://img.tnblog.net/arcimg/hb/bc499cce91de41a5a850e6c9c713fafc.png) ><font style="color:#f1c40f;font-weight:bold;">launchSettings.json</font> ```json { "profiles": { "ConfigurationEnvironmentVariablesDemo": { "commandName": "Project", "environmentVariables": { "XIAO_KEY1": "xiao key1", "KEY1": "value1", "SECTION1_KEY#": "value3", "KEY2": "value2" } } } } ``` ><font style="color:#2ecc71;font-weight:bold;">Program.cs</font> ```csharp var builder = new ConfigurationBuilder(); builder.AddEnvironmentVariables(); var configurationRoot = builder.Build(); Console.WriteLine($"key1:{configurationRoot["key1"]}"); ``` >###运行结果 ![运行结果](https://img.tnblog.net/arcimg/hb/bf61d3e950794faebfd670c6c4760acf.png) <br/> 分层键 ------------ <br/> >###添加代码 ```csharp #region 分层键 var section = configurationRoot.GetSection("SECTION1"); Console.WriteLine($"KEY3:{section["KEY3"]}"); #endregion ``` >###运行结果 ![运行结果](https://img.tnblog.net/arcimg/hb/0e0d3e707d044435b503e847699cdbaa.png) >多层请用冒号(:)隔开,列如:`var section = configurationRoot.GetSection("SECTION1:SECTION2");` 前缀过滤 ------------ <br/> >###特点 <br/> >- 过滤后的环境变量进行注入到 **Build** 中 <br/> >###修改代码 ```csharp var builder = new ConfigurationBuilder(); #region 前缀过滤 builder.AddEnvironmentVariables("XIAO_"); var configurationRoot = builder.Build(); Console.WriteLine($"key1:{configurationRoot["key1"]}"); #endregion ``` >###运行结果 ![运行结果](https://img.tnblog.net/arcimg/hb/d2b5d577a1a042488a3f3be00184b689.png)