从 appsettings.json 公共文件中获取值 class

Get Value from appsettings.json file in common class

我想使用 appsettings.json 文件中的 Appsettings 获取价值

我的代码在 appsettings.json 文件中:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AppSettings": {
    "APIURL": "https://localhost:44303/api"
  },
  "AllowedHosts": "*"
}

但我不知道如何在通用 class 文件中获取该值。

一般来说,要使用strongly-typed配置。本质上,您只需创建一个 class,例如:

public class AppSettings
{
    public Uri ApiUrl { get; set; }
}

然后,在 ConfigureServices:

services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

然后,在你需要使用它的地方,你会注入 IOptions<AppSettings>:

public class Foo
{
    private readonly IOptions<AppSetings> _settings;

    public Foo(IOptions<AppSettings> settings)
    {
        _settings = settings;
    }

    public void Bar()
    {
        var apiUrl = _settings.Value.ApiUrl;
        // do something;
    }
}

创建一个 class 匹配您的 JSON 结构,并将其放在 "common" 位置:

public class AppSettings
{
    public Uri APIURL { get; set; }
}

在某处创建一个 AppSettings 的实例(我喜欢做的是在 ConfigureServices 中创建它,然后将其注册到容器中)。例如

// create a new instance
var appsettings = new AppSettings();
// get section from the config served up by the various .NET Core configuration providers (including file JSON provider)
var section = Configuration.GetSection("AppSettings");
// bind (i.e. hydrate) the config to this instance
section.Bind(appsettings);
// make this object available to other services
services.AddSingleton(appsettings);

然后,当您需要使用 appsettings 时,您只需将其注入任何需要它的服务即可。例如

public class SomeService
{
    private readonly AppSettings _settings;

    public SomeService(AppSettings settings) => _settings = settings;

    ...
}