我正在 Docker 中(在 Kubernetes 中)运行一个 .NET Core 应用程序,将环境变量传递给 Docker 容器并在我的应用程序中使用它们。
在我的 .NET Core 应用程序中,我有以下 C# 类:
public class EnvironmentConfiguration
{
public string EXAMPLE_SETTING { get; set; }
public string MY_SETTING_2 { get; set; }
}
appsettings
像这样:config.
AddJsonFile("appsettings.json").
AddJsonFile($"appsettings.docker.json", true).
AddEnvironmentVariables();
services.Configure<EnvironmentConfiguration>(Configuration);
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/my")]
public class MyController : Controller
{
private readonly IOptions<EnvironmentConfiguration> _environmentConfiguration;
public MyController(IOptions<EnvironmentConfiguration> environmentConfiguration)
{
_environmentConfiguration = environmentConfiguration;
}
}
docker run -p 4000:5000 --env-file=myvariables
myvariables
看起来像这样:EXAMPLE_SETTING=example!!!
MY_SETTING_2=my-setting-2!!!!
_environmentConfiguration
并看到我的变量已设置。services.Configure<EnvironmentConfiguration>(settings => Configuration.GetSection("EnvironmentConfiguration").Bind(settings));
services.Configure<EnvironmentConfiguration>(Configuration);
EnvironmentConfiguration
继承类并使用单独的 DI 注入(inject)两个单独的配置,然后在代码中“手动”合并它们,但这种解决方案是不可取的。
config.
AddJsonFile("appsettings.json").
AddJsonFile("appsettings.docker.json", true).
AddEnvironmentVariables();
{
"Logging": {
"Level": "Debug"
}
}
Logging.Level
的值通过设置名为 Loggingevel
的环境变量到您的偏好值。:
用于在环境变量键中指定嵌套属性。If a colon ( can't be used in environment variable names on your system, replace the colon ( with a double-underscore (__).
关于docker - 在 .NET Core 中将应用设置与环境变量合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48298284/
欢迎光临 OStack程序员社区-中国程序员成长平台 (http://ostack.cn/) | Powered by Discuz! X3.4 |