从通用类的appsettings.json文件中获取价值

时间:2019-05-08 06:57:29

标签: c# asp.net-core asp.net-core-2.2

我想通过appsettings.json文件中的Appsettings获得价值

我的代码在appsettings.json文件中

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

但是我不知道如何在普通类文件中获得该值。

2 个答案:

答案 0 :(得分:1)

通常,您要使用强类型配置。本质上,您只需创建一个像这样的类:

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;
    }
}

答案 1 :(得分:1)

创建一个与JSON结构匹配的类,并将其放在“通用”位置:

Action : 3
Comedy : 2
History : 2
Horror : 2
Romance : 2
Adventure : 1

在某个地方创建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