应用程序的工作方式:
选项1-从应用程序设置加载项目选项2-包括新项目
如果选择“选项1”,则显示项目。这行得通。所以...我使用“选项2”添加了一个新项目。这行得通。但是,如果我选择“选项1”以显示itens,则列表为空。
我的设置
"app": {
"hosts": [
{
"ip": "127.0.0.1",
"hostname": "NotFound"
},
{
"ip": "127.0.0.1",
"hostname": "MyProject"
},
{
"ip": "127.0.0.1",
"hostname": "AnotherProject.dev"
}
]
}
}
进行绑定
AppSettingsModel appSettings = new AppSettingsModel();
Configuration.Bind("app", appSettings);
我将appsettings配置为reloadOnChange
static IConfiguration LoadConfiguration() =>
new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false, true)
.Build();
更新应用设置
var appSettings = new AppSettingsModel();
var appSettings = new AppSettingsModel();
Configuration.Bind("app", appSettings);
appSettings.Hosts.Add(new HostsModel()
{
Ip = "102.54.94.97",
Hostname = "rhino.acme.com"
});
var jsonSerializerOptions = new JsonSerializerOptions()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
var resultC = JsonSerializer.Serialize(appSettings, jsonSerializerOptions);
File.WriteAllText("appsettings.json", resultC);
步骤:
确认是否有以下nuget包
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.FileExtensions
Microsoft.Extensions.Configuration.Json
您需要手动创建和添加appsettings.json(如果不存在)并将copy it to output directory
设置为copy if newer
AppSetting.json
{
"ConnectionStrings": {
"BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
},
}
Program.cs(访问AppSettings的ConnectionStrings
)>
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
IConfigurationRoot configuration = builder.Build();
Console.WriteLine(configuration.GetConnectionString("BloggingDatabase"));
}