[英]How to use properly ConfigurationManager.GetSection() in .Net Core 2.2
I am having some problems for getting the configuration values using this method in my web application in .net core. 我在.net核心的Web应用程序中使用此方法获取配置值时遇到一些问题。
var settings = ConfigurationManager.GetSection("JwtBearerSettings/Issuer");
This method is called by one project I am referencing. 我正在引用的一个项目调用此方法。 It is also in .NET Core 2.2 and the config settings are on the file
它也在.NET Core 2.2中,并且配置设置在文件中
appsettings.json
appsettings.json
The thing is that when I am debugging always I get settings == null
I have been looking for similar questions but I couldn't solve this. 问题是,当我总是调试时,我会得到
settings == null
我一直在寻找类似的问题,但是我无法解决。
My json is 我的json是
{
"JwtBearerSettings": {
"Issuer": "Auth.MyStuff.Api",
"PrivateKey": "Blablabla",
"ExpirationTime": "15"
}
}
Do you know if is even possible to use this method? 您知道甚至可以使用这种方法吗?
Am I missing something between, for getting the web app configuration with my library? 我是否缺少使用图书馆获取Web应用程序配置的功能?
Given that you've created a property like this: 鉴于您已经创建了如下属性:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
}
You can then access the elements, like this: 然后,您可以访问元素,如下所示:
var issuer = Configuration["JwtBearerSettings:Issuer"],
The simplest way to read config out is to simply read out a value at a time. 读取配置的最简单方法是一次仅读取一个值。 Structured data is separated by colons, so your example becomes:
结构化数据用冒号分隔,因此您的示例变为:
var issuer = Configuration["JwtBearerSettings:Issuer"];
This is clearly a pain if you are reading a lot of settings. 如果您正在阅读许多设置,显然这很痛苦。 So you can instead simply Bind a model object to a section.
因此,您可以简单地将模型对象绑定到部分。 For example, if you had a model object with properties in it, say
例如,如果您有一个带有属性的模型对象,则说
class JwtBearerSettings {
public string Issuer {get;set;}
}
then you can use GetSection
to bind to a settings object: 然后可以使用
GetSection
绑定到设置对象:
var jbs = new JwtBearerSettings();
Configuration.GetSection("JwtBearerSettings").Bind(jbs);
This pattern is used by a lot of libraries as it lets you provide as little, or as much config as you need - as long as the model is pre-filled with sensible defaults. 许多库都使用此模式,因为它允许您根据需要提供尽可能少的配置,只要模型中预先填充了合理的默认值即可。
The third pattern supported .Net Core can be used with DI: 支持的第三个模式.Net Core可以与DI一起使用:
Here you can register your configuration model with the service factory: 您可以在此处向服务工厂注册配置模型:
var jbs = Configuration.GetSection("JwtBearerSettings");
services.Configure<JwtBearerSettings>(jbs);
and, to reference your settings in a service, simply add IOptions as a ctor parameter: 并且,要引用服务中的设置,只需将IOptions添加为ctor参数即可:
public MyService(IOptions<JwtBearerSettings> jwtOptions)
{
Config = jwtOptions.Value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.