如何在 .NET Core 的 Startup class 构造函数中访问 AppSettings

How to access AppSettings in Startup class constructor in .NET Core

我正在尝试从配置文件添加 SeriLog 设置,例如最低日志级别和滚动文件路径。标准是像这样硬编码它们:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();

    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Debug()
        .WriteTo.RollingFile("C:/LogFiles/log-{Date}.txt")
        .CreateLogger();
}

基本上,我需要能够在 Startup 构造函数中访问 appsettings.json 中的值。像这样:

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Is((LogEventLevel)Enum.Parse(typeof(LogEventLevel),
        Configuration.GetValue<string>("AppSettings.MinimumLoggingLevel")))
    .WriteTo.RollingFile(Configuration.GetValue<string>("AppSettings.RollingFilePath"))

我在另一个 SO post 中找到了 Configuration.GetValue 语法,但它总是 returns null.

如果AppSettings部分是这样的:

"AppSettings": {
    "RollingFilePath": "..."
},

然后将 . 更改为 :

.WriteTo.RollingFile(Configuration.GetValue<string>("AppSettings:RollingFilePath"))

或者使用这个

.WriteTo.RollingFile(Configuration["AppSettings:RollingFilePath"])

我的 appsettings.json 看起来像这样:

{
   "Logging": {
   "IncludeScopes": false,
   "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
      }
   }
}

要访问一个值,我可以使用这样的东西:

var IncludeScopes = Configuration.GetValue<bool>("Logging:IncludeScopes", true);