来源: ASP.NET Core如何不重启获取更改后的配置_windowsliusheng的专栏-CSDN博客
1.appsettings.json配置文件中配置数据
{
“UserName”: “Admin”
}
2.Startup文件Configure方法中添加以下配置(热更新主要使用的ChangeToken.OnChange方法通知设置的回调方法来达到及时更新)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
IConfigurationRoot configurationRoot;
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
configurationRoot = new ConfigurationBuilder().AddJsonFile(“appsettings.Development.json”, true, true).Build();
}
else
{
configurationRoot = new ConfigurationBuilder().AddJsonFile(“appsettings.json”, true, true).Build();
}
//string environment = Environment.GetEnvironmentVariable(“ASPNETCORE_ENVIRONMENT”);
//获取配置
GetAppSettingsModel(configurationRoot.Get<AppSettingsModel>());
//配置文件更新后回调更新方法
ChangeToken.OnChange(() => configurationRoot.GetReloadToken(), () =>
{
GetAppSettingsModel(configurationRoot.Get<AppSettingsModel>());
});
}
public void GetAppSettingsModel(AppSettingsModel appSettings)
{
AppSettingsConfig.UserName = appSettings.UserName;
Console.WriteLine($”UserName:{ appSettings.UserName}”);
}
//配置文件实体模型
public class AppSettingsModel
{
public string UserName { get; set; }
}
//配置文件数据
public class AppSettingsConfig
{
public static string UserName { get; set; }
}
注:不同读取方式请参考:https://www.cnblogs.com/libingql/p/11326358.html
————————————————
版权声明:本文为CSDN博主「windowsliusheng」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/windowsliusheng/article/details/107094967