2019年2月25日 星期一

ASP.NET Core (包含 .NET Core)依據組態為 Release 或 Debug 取得各自的設定內容

首先取得目前的組態,如下列的程式碼:
原理可以參考這篇:怎樣判斷 .NET Core (包含 ASP.NET Core)是 Debug 或 Release ?
  1. public static class DebuggingProperties
  2. {
  3. ///
  4. /// 檢查當前正在運行的程式組態。
  5. ///
  6. public static string Config
  7. {
  8. get
  9. {
  10. if (_ConfigAttribute == null)
  11. {
  12. var assembly = Assembly.GetEntryAssembly();
  13. if (assembly == null)
  14. {
  15. // 由於調用 GetFrames 的 StackTrace 實例沒有跳過任何幀,所以 GetFrames() 一定不為 null。
  16. assembly = new StackTrace().GetFrames().Last().GetMethod().Module.Assembly;
  17. }
  18. var assemblyConfigurationAttribute = assembly.GetCustomAttribute();
  19. _ConfigAttribute = assemblyConfigurationAttribute.Configuration;
  20. }
  21. return _ConfigAttribute;
  22. }
  23. }
  24. private static string _ConfigAttribute;
  25. }
appsettings.json 檔案設定格式如下:
  1. {
  2. "Release": {
  3. "DefaultConnection": " Release Server"
  4. },
  5. "Debug": {
  6. "DefaultConnection": "Debug Server"
  7. }
  8. }
需要組態設定時,只要如下呼叫即可: 在 Startup.cs 新增下列程式碼:
  1. public IConfiguration _config { get; }
  2.  
  3. // 取的 appsettings.json 的設定
  4. public Startup(IConfiguration configuration)
  5. {
  6. _config = configuration;
  7. }
  8.  
  9.  
  10. // 執行中取得組態設定的方式
  11. public void Run()
  12. {
  13. // 取的 appsettings.json 的 Release 或 Debug 組態設定
  14. var cfg_ = _config.GetSection(DebuggingProperties.Config);
  15. // 取的 appsettings.json 指定組態設定內容
  16. string def_ = cfg_ .GetValue("DefaultConnection");
  17. }

Visual Studio 2017/2019 推薦的擴充功能與更新

參考文章: 覺得 Google 的 Blogger 不太順手?透過 HTML 的 iframe 移花接木 HackMD