原理可以參考這篇:怎樣判斷 .NET Core (包含 ASP.NET Core)是 Debug 或 Release ?
appsettings.json 檔案設定格式如下:
public static class DebuggingProperties
{
///
/// 檢查當前正在運行的程式組態。
/// public static string Config
{
get
{
if (_ConfigAttribute == null)
{
var assembly = Assembly.GetEntryAssembly();
if (assembly == null)
{
// 由於調用 GetFrames 的 StackTrace 實例沒有跳過任何幀,所以 GetFrames() 一定不為 null。
assembly = new StackTrace().GetFrames().Last().GetMethod().Module.Assembly;
}
var assemblyConfigurationAttribute = assembly.GetCustomAttribute
();
_ConfigAttribute = assemblyConfigurationAttribute.Configuration;
}
return _ConfigAttribute;
}
}
private static string _ConfigAttribute;
}
需要組態設定時,只要如下呼叫即可: 在 Startup.cs 新增下列程式碼:
{
"Release": {
"DefaultConnection": " Release Server"
},
"Debug": {
"DefaultConnection": "Debug Server"
}
}
- public IConfiguration _config { get; }
- // 取的 appsettings.json 的設定
- public Startup(IConfiguration configuration)
- {
- _config = configuration;
- }
- // 執行中取得組態設定的方式
- public void Run()
- {
- // 取的 appsettings.json 的 Release 或 Debug 組態設定
- var cfg_ = _config.GetSection(DebuggingProperties.Config);
- // 取的 appsettings.json 指定組態設定內容
- string def_ = cfg_ .GetValue
("DefaultConnection"); }
沒有留言:
張貼留言