简体   繁体   中英

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.

 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

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.

My json is

{
     "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?

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:

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:

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:

public MyService(IOptions<JwtBearerSettings> jwtOptions)
{
    Config = jwtOptions.Value;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM