【问题标题】:How do I get the value of a setting in appsettings.json from configuration in programs.cs Blazor app如何从programs.cs Blazor应用程序中的配置中获取appsettings.json中设置的值
【发布时间】:2022-01-06 18:26:09
【问题描述】:

谁能告诉我如何从 Blazor(核心 5)应用程序的 program.cs 文件中的 appsettings.json 文件中获取值。 基本上只需要正确写出“var seqUrl =”。我认为。 请和谢谢。

在我的 Program.cs 的 Main 方法中,我有

IConfiguration configuration = new ConfigurationBuilder()                
            .AddJsonFile("appsettings.json", false, true)
            .AddJsonFile("appsettings.Development.json", true, true)
            .Build();
        var levelSwitch = new LoggingLevelSwitch();
        var seqUrl = configuration.GetSection("SeriLog").GetSection("WriteTo").GetSection("Name:Seq").GetSection("Args").GetSection("serverUrl").Value;
        Log.Logger = new LoggerConfiguration()
            .ReadFrom.Configuration(configuration)
            .MinimumLevel.ControlledBy(levelSwitch)
            .WriteTo.Seq(seqUrl, 
            apiKey: "xxxxxxxxxxxx",
            controlLevelSwitch: levelSwitch)
            .CreateLogger();

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

"SeriLog": {
"Using": [
  "Serilog.Sinks.File",
  "Serilog.Sinks.Seq",
  "Serilog.Sinks.Console"
],
"MinimumLevel": {
  "Default": "Information",
  "Override": {
    "Microsoft": "Warning",
    "system": "Warning"
  }
},
"Enrich": [ "WithMachineName", "WithEnvironmentUserName", "WithClientIp", "WithClientAgent", "WithEnvironmentName", "WithProcessId", "WithProcessName", "WithThreadId" ],

"WriteTo": [ 
  {
    "Name": "File",
    "Args": {
      "path": "C:\\Temp\\Logs\\JsonLog.json",
      "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog",
      "rollingInterval": "Day"
    }
  },
  {
    "Name": "Seq",
    "Args": {
      "serverUrl": "http://xxxxxxxxxxx" 
    }
  }     
]

【问题讨论】:

  • 为什么你的命令中有.GetSection("Name:Seq")?没有这样的部分,右侧的外观不是“名称”的子项。
  • 好问题...我知道这是错的,这就是为什么我问是否有人知道如何正确地写那行。

标签: c# configuration blazor settings


【解决方案1】:

我认为您应该考虑在您的 appsettings 文件中重构 JSON。 “WriteTo”的值是一个数组,但我会将它设为一个对象而不是一个数组,那么每个元素都应该是一个子对象。使用“名称”变量来命名它们。像这样:

"WriteTo": { 
    "File": {
        "Args": {
        "path": "C:\\Temp\\Logs\\JsonLog.json",
        "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog",
        "rollingInterval": "Day"
        }
    },
    "Seq": {
        "Args": {
        "serverUrl": "http://xxxxxxxxxxx" 
        }
    }     
}

然后您应该能够使用与您相同的样式检索值,只需使用所需变量的完整路径即可。例如:

var seqUrl = configuration.GetSection("SeriLog:WriteTo:Seq:serverUrl").Value; 我不记得这个语法是否 100% 正确(路径可能不是冒号分隔的,我不完全确定)但这个概念应该有效。您只是没有在代码中的 .GetSection() 方法中输入正确的名称,我认为当您尝试检索这样的数组元素时会有点棘手,因此我建议从数组转换为简单对象.

【讨论】:

  • 工作就像一个魅力,谢谢....
猜你喜欢
  • 1970-01-01
  • 2021-01-27
  • 1970-01-01
  • 2021-05-31
  • 2016-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多