[英]How to replace list items in a custom appsettings.json file?
我有針對每個環境的自定義 appsettings.json 文件,所以 appsettings.Dev.json、appsettings.Test.json、appsettings.Prod.json。 在主 appsettings.json 中,我有以下代碼:
"EmailSettings": {
"Recipients": [
"person@test.com"
]
}
然后在自定義 json 文件中,我想覆蓋這個列表,如下所示:
"EmailSettings": {
"Recipients": [
"anotherperson@test.com"
]
}
但相反,它會像這樣附加:
"EmailSettings": {
"Recipients": [
"person@test.com",
"anotherperson@test.com"
]
}
對於所有其他類型的設置,它們會被替換,但出於某種原因,自定義設置文件中的列表似乎被附加了。 使用 .net,您曾經使用 xslt 有更多的粒度,以便能夠確定是要替換還是附加覆蓋的設置。 這里有什么建議嗎?
我這樣做了,它在自定義 json 設置中被替換了。 主要的 appsettings.json:
"EmailSettings": {
"Recipients:0": "person@test.com"
}
然后在自定義設置文件中:
"EmailSettings": {
"Recipients:0": "anotherperson@test.com"
}
感謝您的回復!
我為環境(包括Development
)使用了不同的appsettings
文件
所以首先確保你已經在你的配置中添加了環境 json 文件:
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{EnvironmentName}.json", optional: true, reloadOnChange: true)
然后在我原來的appsettings.json
它會是這樣的:
"EmailSettings": {
"Recipients": []
}
然后用於本地開發( Development
環境): appsettings.Development.json
"EmailSettings": {
"Recipients": [
"person@test.com"
]
}
然后對於其他環境(我們稱之為Staging
): appsettings.Staging.json
"EmailSettings": {
"Recipients": [
"anotherperson@test.com"
]
}
然后,只需確保在您的其他環境中已在環境變量中設置了ASPNETCORE_ENVIRONMENT
。
在appsettings.Test.json
使用以下內容
"EmailSettings:Recipients:0" : "anotherperson@test.com"
配置 API 能夠通過使用配置鍵中的分隔符扁平化分層數據來維護分層配置數據。
您將需要定義電子郵件設置類,如
public class EmailSettings
{
public List<string> Recipients { get; set; }
}
並連接 DI 以在Startup
類的Configure
方法中添加選項
public void ConfigureServices(IServiceCollection services)
{
// add Options
services.AddOptions();
services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.