首页 > 解决方案 > 静态类中的 Asp.Net Core 配置

问题描述

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

private static string Url => ConfigurationManager.GetSection("Urls/SampleUrl").ToString();

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

  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionStrings": {
    "cs1": "some string",
    "cs2": "other string"
  },
  "Urls": {
    "SampleUrl": "google.com"
  },
  "AllowedHosts": "*"

我只是想从 appsettings 中读取一些数据。根据文档,我不应该以某种方式注册我的标准 appsettings.json 文件,因为Host.CreateDefaultBuilder(args)在 Program 类中默认情况下会为我执行此操作。

标签: c#asp.net-coreconfiguration

解决方案


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

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

public static IConfiguration StaticConfig { get; private set; }

并在静态类中使用:

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


推荐阅读