静态类中的 Asp.Net Core 配置

Nic*_*fsf 1 c# configuration asp.net-core

我想从静态类中的 appsettings.json 文件中读取 url。我尝试过类似的东西

private static string Url => ConfigurationManager.GetSection("Urls/SampleUrl").ToString();
Run Code Online (Sandbox Code Playgroud)

但每当我尝试调用GetSection()方法时,我都会得到空值。

  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionStrings": {
    "cs1": "some string",
    "cs2": "other string"
  },
  "Urls": {
    "SampleUrl": "google.com"
  },
  "AllowedHosts": "*"
Run Code Online (Sandbox Code Playgroud)

我只是想从应用程序设置中读取一些数据。根据文档,我不应该以某种方式注册我的标准 appsettings.json 文件,因为Host.CreateDefaultBuilder(args)在 Program 类中默认为我注册。

Mat*_*ech 5

正如这里提到的,您可以将静态属性添加到您的Startup.cs

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
    StaticConfig = configuration;
}

public static IConfiguration StaticConfig { get; private set; }
Run Code Online (Sandbox Code Playgroud)

并在静态类中使用:

var x = Startup.StaticConfig.GetSection("whatever");

  • 问题是我使用静态类,所以我不能简单地注入 ``` IConfiguration ``` 来调用 ``` GetValue() ``` 方法。我也无法在“配置”上使用 [],因为它没有提供执行此操作的方法。调用``ConfigurationManager.AppSettings```也没有帮助 (2认同)