[英]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.