使用 ENV 变量在 appsettings.json 中设置键 - ASP.NET Core 3.1 Docker

use*_*598 3 c# environment-variables docker asp.net-core

我有一个 .NET Core Web API,我试图找出如何使用 ENV 变量来配置我的密钥,appsetttings.json这样我就可以在创建 Docker 容器时填充数据。

到目前为止,我已经成功地注入IOptions<>了我的测试控制器,并且能够调试这些值为 NULL 的值,因为应用程序目前还没有在容器中运行。

测试控制器:

namespace TestWebApplication.Controllers
{
    [ApiController]
    [Route("api/")]
    public class TestController : ControllerBase
    {
        private readonly IOptions<EnvironmentConfiguration> _environmentConfiguration;

        public TestController(IOptions<EnvironmentConfiguration> environmentConfiguration)
        {
            _environmentConfiguration = environmentConfiguration;
        }

        [HttpGet]
        [Route("testmessage")]
        public ActionResult<string> TestMessage()
        {
            var test = _environmentConfiguration.Value;

            return Ok($"Value from EXAMPLE_1 is {test.EXAMPLE_1}");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

环境配置:

namespace TestWebApplication.Models
{
    public class EnvironmentConfiguration
    {
        public string EXAMPLE_1 { get; set; }
        public string EXAMPLE_2 { get; set; }
     }
}
Run Code Online (Sandbox Code Playgroud)

在学习了一些较旧的教程之后,我注意到我实际上从来不需要为此添加任何代码ConfigureServices

例如,假设我有我的这一部分appsettings.json

"eureka": {
    "client": {
      ......
    },
    "instance": {
      "port": "xxxx",
      "ipAddress": "SET THIS WITH ENV",
    }
  }
Run Code Online (Sandbox Code Playgroud)

我怎么能设置一个环境变量来填充ipAddress所以当我去 Docker 时,我运行这样的东西:

docker run .... -eEXAMPLE_1 -e IP_ADDRESS ....

mtk*_*nko 6

例如,您有一个部分appsettings.json

{
    "Section1" : {
        "SectionA": {
            "PropA": "A",
            "PropB": "B"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

和一个班级:

public class SectionA
{
    public string PropA { get; set; }
    public string PropB { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Startup.cs映射类到部分能够注入IOptions<SectionA>

services.Configure<SectionA>(Configuration.GetSection("Section1:SectionA"));
Run Code Online (Sandbox Code Playgroud)

然后,您可以覆盖SectionA使用此环境变量命名约定的属性:Section1__SectionA__PropA.

另请阅读此https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1#keys