在.NET Core中将应用程序设置与环境变量合并 [英] Merging appsettings with environment variables in .NET Core
问题描述
我正在Docker中(在Kubernetes中)运行.NET Core应用程序,将环境变量传递给Docker容器并在我的应用程序中使用它们.
I am running a .NET Core app in Docker (in Kubernetes), passing environment variables to the Docker container and using them in my app.
在我的.NET Core应用程序中,我具有以下C#类:
In my .NET Core app I have the following C# class:
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();
DI设置:
services.Configure<EnvironmentConfiguration>(Configuration);
然后在我的控制器中按如下方式使用它:
And in my Controller I use it as such:
[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:
docker run -p 4000:5000 --env-file=myvariables
文件myvariables
看起来像这样:
EXAMPLE_SETTING=example!!!
MY_SETTING_2=my-setting-2!!!!
这有效.我可以使用_environmentConfiguration
并看到设置了我的变量.
This works. I can use my _environmentConfiguration
and see that my variables are set.
但是...我想将环境变量与appsettings合并,以便在未找到环境变量时将appsettings中的值用作备用.以某种方式合并这两行:
However... I would like to merge environment variables with appsettings so that the values from appsettings are used as fallback when environment variables are not found. Somehow merging these two lines:
services.Configure<EnvironmentConfiguration>(settings => Configuration.GetSection("EnvironmentConfiguration").Bind(settings));
services.Configure<EnvironmentConfiguration>(Configuration);
这有可能吗?
我的后备计划是从EnvironmentConfiguration
类继承,并使用单独的DI注入两个单独的配置,然后在代码中手动"合并它们,但这是不可取的.
My fallback plan is to inherit from the EnvironmentConfiguration
class and use a separate DI to have two separate configurations injected and then merge them "manually" in code but this solution is undesirable.
推荐答案
config.
AddJsonFile("appsettings.json").
AddJsonFile("appsettings.docker.json", true).
AddEnvironmentVariables();
实际上足以使用环境变量覆盖应用设置值.
is actually enough to override appsettings values using environment variables.
假设您的appsettings.json文件中包含以下内容;
Let's say you have the following in your appsettings.json file;
{
"Logging": {
"Level": "Debug"
}
}
您可以通过将名为Logging:Level
的环境变量设置为您的首选项值来覆盖Logging.Level
的值.
you can override value of Logging.Level
by setting the environment variable named Logging:Level
to the value of your preference.
请注意,:
用于指定环境变量键中的嵌套属性.
Be aware that :
is used to specify nested properties in environment variable keys.
Also note: from docs;
如果不能在系统的环境变量名称中使用冒号(:),请用双下划线(__)替换冒号(:).
这篇关于在.NET Core中将应用程序设置与环境变量合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!