用于登录 appsettings.json (.net6) 的 IOptionsMonitor 返回旧值/默认值

问题描述 投票:0回答:2

我正在尝试使用 IOptionsMonitor 在运行时在 appsettings.json 中更改 ILogger 日志级别,但尽管我已将 IOptionsMonitor 用于其他设置(例如应用程序中使用的电子邮件设置),在这种情况下它会返回旧值或默认值..

我可以更改值,我可以打开 appsettings.json 来查看值已更改,但从 appsettings.json 加载值会返回默认值。以前有人遇到过此问题吗?

IOptionsMonitor 映射类:

public class LoggingSettings
    {
        public const string SectionName = "Logging";

        public LogLevelSettings LogLevel { get; set; }
    }

public class LogLevelSettings
    {
        public const string SectionName = "LogLevel";

        [ConfigurationKeyName(name: "Default")]
        public string DefaultSetting { get; set; }

        [ConfigurationKeyName(name: "Microsoft.AspNetCore")]
        public string MicrosoftAspNetCore { get; set; }
    }

appsettings.json 中的部分:

 "Logging": {
    "LogLevel": {
      "Default": "Critical",
      "Microsoft.AspNetCore": "None"
    }
  }

摘自 LogSettingsModel.cshtml.cs 构造函数(页面):

public LogSettingsModel(IOptionsMonitor<LoggingSettings> logSettings)
{
            //this returns values "Information" and "Warning" for "Default" and "Microsoft.AspNetCore" keys instead "Critical" and "None"
            _logSettings = logSettings.CurrentValue;

            //this also returns "Information" for "Default" key, configurationHelper is static class made for accessing options..
            var sec = ConfigurationHelper.config.GetSection("Logging:LogLevel:Default");

        }

ConfigurationHelper 类(如果我需要从静态方法访问配置并进行测试,则创建):

public static class ConfigurationHelper
    {
        public static IConfiguration config;
        public static IWebHostEnvironment env;

        public static void Initialize(IConfiguration configuration, IWebHostEnvironment environment)
        {
            config = configuration;
            env = environment;
        }
}

我注意到这个问题似乎发生了,因为所有其他设置都是从“appsettings.json”加载的(在本地运行时) - 但这个特定值(我相信)是从“appsettings.Development.json”加载的,不知道为什么会这样正在发生。因此,如果我在 appsettings.json 中手动将 LogLevel:Default 更改为“None”,它仍然会加载设置“Information”。

使用在 LogSettingsModel.cshtml.cs 设置的调试器断点进行检查时,我可以看到 appsettings.Development.json 中有设置。

似乎当 appsettings.Development.json 内部有一些值时,会加载该值而不是 appsettings.json 值。

c# asp.net-core .net-6.0 razor-pages
2个回答
1
投票

appsettings.development.json 不是“隐藏”的。 IConfiguration 是键值字典。后面的配置提供程序提供的键值会覆盖前面的值。默认情况下,

appsettings.Development.json
appsettings.json
之后加载。因此,如果两个文件中都存在某个键,则
appsettings.json
中的值将被覆盖。就这样。 只是一点注释:appsettings.Development.json 仅在开发环境中加载。


0
投票

我忘记了 appsettings.development.json 是“隐藏”在 appsettings.json 下的。 似乎 appsettings.Development.json (在本地开发中)优先于 appsettings.json,并且 appsettings.json 中的值被 appsettings.Development.json 中的值覆盖。 感谢所有参与者的宝贵时间!

© www.soinside.com 2019 - 2024. All rights reserved.