在 Java 中,我使用一个名为
application.properties
的文件,我可以在其中引用这样的环境变量
database.url=${DATABASE_URL}
在 .NET 7 中,我们使用
appsettings.json
来定义应用程序的配置。
在我的具体情况下,Azure 将把所有这些配置值存储在 Keyvault 中,该 Keyvault 将用作我的 .NET 7 应用程序的环境变量。我不知道 keyvault 中存储的任何值,因此为每个环境提供一个包含所有内容的 appsettings 文件不是一种选择。
我需要的是类似于Java中发生的事情,我想象的是这样的:
appsettings.json
:
{
"DatabaseUrl":"${DATABASE_URL}"
}
有办法实现这一点吗?或者也许有另一种方法可以用环境变量替换此配置值。
var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile($"appsettings.json", optional: false)
.AddJsonFile($"appsettings.{env}.json", optional: true)
.AddEnvironmentVariables()
.Build();
var databaseUrl = configuration.GetSection("DatabaseUrl");
您只需在 launchSettings 中添加更多 EnvVar,例如 AN_ENVVAR_ENDPOINT:
"profiles": {
"MyApp": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7034;http://localhost:5034",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"AN_ENVVAR_ENDPOINT": "https://localhost:7052/v4.0/Version"
}
},
我在C#中这样使用
{ "DatabaseUrl":"$env:DATABASE_URL" }