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



我有一个.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}");
}
}
}

环境配置:

namespace TestWebApplication.Models
{
public class EnvironmentConfiguration
{
public string EXAMPLE_1 { get; set; }
public string EXAMPLE_2 { get; set; }
}
}

在学习了一些旧的教程之后,我注意到我实际上从来没有需要在ConfigureServices中放入任何代码来实现这一点。

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

"eureka": {
"client": {
......
},
"instance": {
"port": "xxxx",
"ipAddress": "SET THIS WITH ENV",
}
}

我如何设置一个环境变量来填充ipAddress,这样当我进入Docker时,我会运行这样的东西:

docker运行-e EXAMPLE_1-e IP_ADDRESS。。。。

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

{
"Section1" : {
"SectionA": {
"PropA": "A",
"PropB": "B"
}
}
}

和一个类别:

public class SectionA
{
public string PropA { get; set; }
public string PropB { get; set; }
}

Startup.cs中,将类映射到能够注入IOptions<SectionA>:的部分

services.Configure<SectionA>(Configuration.GetSection("Section1:SectionA"));

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

另请阅读https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1#密钥

最新更新