I have a .NET Core Web API and I am trying to find out how to use ENV variables to configure keys in my appsetttings.json so I can then populate with data when creating a Docker container.
So far I have managed to inject IOptions<> into my test controller and I was able to debug the values, which were NULL because the app is currently not running in a container just yet.
Test controller:
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}");
}
}
}
Environment configuration:
namespace TestWebApplication.Models
{
public class EnvironmentConfiguration
{
public string EXAMPLE_1 { get; set; }
public string EXAMPLE_2 { get; set; }
}
}
After following some older tutorials I noticed I actually never needed to put any code in ConfigureServices for this to work.
For example, lets say I have this part of my appsettings.json:
"eureka": {
"client": {
......
},
"instance": {
"port": "xxxx",
"ipAddress": "SET THIS WITH ENV",
}
}
How could I set an environment variable to populate the ipAddress so when I go to Docker, I run something like this:
docker run .... -e EXAMPLE_1 -e IP_ADDRESS ....