这是我的appsettings.json
{
"MySettings": {
"DefaultSetting": "Key1",
"Settings": {
"Key1": {
"Full": "Description1",
"Short": "Desc1"
},
"Key2": {
"Full": "Description2",
"Short": "Desc2"
},
"Key3": {
"Full": "Description3",
"Short": "Desc3"
}
}
}
}
我的班级定义:
public class MySettings
{
public Dictionary<string, Setting> Settings { get; set; }
public string DefaultSetting { get; set; }
}
public class Setting
{
public string Full { get; set; }
public string Short { get; set; }
}
My Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.Configure<MySettings>(Configuration.GetSection("MySettings"));
services.AddMvc();
}
在HomeController中:
public class HomeController : Controller
{
private readonly MySettings _mySettings;
public HomeController(IOptionsSnapshot<MySettings> mySettings)
{
this._mySettings= mySettings.Value;
}
public IActionResult Index()
{
return Json(_mySettings.DefaultSetting);
}
}
我希望在保存更改的appsettings.json文件并刷新浏览器时获取新的设置值。
我之前尝试过IOptionsMonitor
参考:http://andrewlock.net/reloading-strongly-typed-options-when-appsettings-change-in-asp-net-core-rc2/
但是我有很多强类型的类,它会注册太多的IOptionsMonitor
是否有更简单的方法来实现自动重新加载强类型类?
答案 0 :(得分:2)
是的,您可以在更改时重新加载appsettings。为此,在启动构造函数中,将 reloadOnChange 指定为true,如下所示 -
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();