【问题标题】:Get Value from appsettings.json file in common class从公共类中的 appsettings.json 文件中获取值
【发布时间】:2019-05-08 23:32:44
【问题描述】:
我想使用 appsettings.json 文件中的 Appsettings 获得价值
我的代码在 appsettings.json 文件中:
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AppSettings": {
"APIURL": "https://localhost:44303/api"
},
"AllowedHosts": "*"
}
但我不知道如何在通用类文件中获取该值。
【问题讨论】:
标签:
c#
asp.net-core
asp.net-core-2.2
【解决方案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;
}
}
【解决方案2】:
创建一个与您的 JSON 结构匹配的类,并将其放在“公共”位置:
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;
...
}