原本在 Asp.Net Mvc中可以使用 ${appsetting} 取得設定值,但在 Asp.Net Core 中卻無法使用
環境
- ASP.NET 5
- NLog.Web.AspNetCore 4.14.0
appsettings.json
{
"AppName": "Test",
"AppSettings": {
"User": "Name"
}
}
Program
透過 LogManager 讀取 appsettings.json
public static void Main(string[] args)
{
var logger = LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
try
{
CreateHostBuilder(args).Build().Run();
}
catch (Exception exception)
{
logger.Error(exception, "Stopped program because of exception");
throw;
}
finally
{
LogManager.Shutdown();
}
}
NLog.config
只需要改用 configsetting
即可
- 取得第一層的參數 AppName:
${configsetting:name=AppName}
- 取得 AppSettings 內的 User:
${configsetting:name=AppSettings.User}
- 嘗試取得,否則拿 default 值:
${configsetting:name=Test:default=123}