我们有一个使用此appsettings.json的ASP.NET核心Web应用程序:
{
"Subscriptions": [
{
"Name": "Production",
"PublishSettings": "<PublishData>SECRET</PublishData>",
"Environments": [
{
"Name": "Prod",
"DeploymentServiceNames": [
"api1",
"api2",
"api3"
]
}
]
},
{
"Name": "Test",
"PublishSettings": "<PublishData>SECRET</PublishData>",
"Environments": [
{
"Name": "Test1",
"DeploymentServiceNames": [
"api1",
"api2"
]
},
{
"Name": "Test2",
"DeploymentServiceNames": [
"api1",
"api2"
]
}
]
}
]
}
PublishSettings
值是保密的,所以我想在我的本地用户机密文件和我的部署的环境变量中使用这些值。但是,因为Subscriptions
是一个数组我不确定如何。我并不特别想换掉整个Subscriptions
部分。有没有办法在这样的数组中为每个项交换单个属性,可能是通过在强类型订阅模型上定义一个键属性?
答案 0 :(得分:2)
当你在.NET Core中加载配置时,它被表示为一组键值对(键和值都有string
类型)由添加的配置提供程序提供。
例如,appsettings.json
将由JsonConfigurationProvider
表示为以下设置列表:
{Subscriptions:0:Environments:0:DeploymentServiceNames:0, api1}
{Subscriptions:0:Environments:0:DeploymentServiceNames:1, api2}
{Subscriptions:0:Environments:0:DeploymentServiceNames:2, api3}
{Subscriptions:0:Environments:0:Name, Prod}
{Subscriptions:0:Name, Production}
{Subscriptions:0:PublishSettings, <PublishData>SECRET</PublishData>}
{Subscriptions:1:Environments:0:DeploymentServiceNames:0, api1}
{Subscriptions:1:Environments:0:DeploymentServiceNames:1, api2}
{Subscriptions:1:Environments:0:Name, Test1}
{Subscriptions:1:Environments:1:DeploymentServiceNames:0, api1}
{Subscriptions:1:Environments:1:DeploymentServiceNames:1, api2}
{Subscriptions:1:Environments:1:Name, Test2}
{Subscriptions:1:Name, Test}
{Subscriptions:1:PublishSettings, <PublishData>SECRET</PublishData>}
如您所见,JSON结构被展平,并且通过使用冒号连接内部节名称来构建键。添加数组元素并使用适当的索引作为名称。
如果您添加其他配置来源,例如环境变量或其他秘密json文件,它将具有相同键的设置,它将覆盖设置。
因此,如果要添加或覆盖PublishSettings
,可以添加另一个JSON文件作为配置源:
{
"Subscriptions": [
{
"PublishSettings": "<PublishData>SECRET</PublishData>"
},
{
"PublishSettings": "<PublishData>SECRET</PublishData>"
}
]
}
或者使用以下键将其添加为环境变量:
Subscriptions:0:PublishSettings
Subscriptions:1:PublishSettings
对于.NET Core配置绑定程序,此类设置覆盖(或添加)是透明的。设置POCO将包含来自提供此类值的最后一个配置源的值PublishSettings
。