簡體   English   中英

使用強類型重新加載 appsettings.json

[英]Reloading appsettings.json using Strongly type

這是我的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; }
}

我的Startup.cs

public void ConfigureServices(IServiceCollection services)
{
  // Add framework services.
  services.AddApplicationInsightsTelemetry(Configuration);
  services.Configure<MySettings>(Configuration.GetSection("MySettings"));
  services.AddMvc();
}

在家庭控制器中:

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

這是參考

但是我有很多強類型類,它會注冊太多IOptionsMonitor

有沒有更簡單的方法來實現自動重載強類型類?

是的,您可以在更改時重新加載應用程序設置。 為此,在啟動構造函數中,像這樣將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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM