简体   繁体   中英

Configuration.GetSection in Asp.Net Core 2.0 getting all settings

I am trying to learn the various ways to retrieve configuration info so I can determine the best path for setting up and using configuration for an upcoming project.

I can access the various single settings using

var sm = new SmsSettings
    {
        FromPhone = Configuration.GetValue<string>("SmsSettings:FromPhone"),               
        StartMessagePart = Configuration.GetValue<string>("SmsSettings:StartMessagePart"),               
        EndMessagePart = Configuration.GetValue<string>("SmsSettings:EndMessagePart")
    };

I also need to be able to count settings, determine values of certain settings etc. So I was building a parsing method to do these types of things and needed a whole section of the settings file, which is what I assumed GetSection did. Wrong.

appsettings file

{
"ConnectionStrings": {
  "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=TestingConfigurationNetCoreTwo;Trusted_Connection=True;MultipleActiveResultSets=true",
  "ProductionConnection": "Server=(localdb)\\mssqllocaldb;Database=TestingConfigurationNetCoreTwo_Production;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
  "IncludeScopes": false,
  "LogLevel": {
    "Default": "Warning"
  }
},   
"SmsSettings": {
  "FromPhone": "9145670987",      
  "StartMessagePart": "Dear user, You have requested info from us on starting",      
  "EndMessagePart": "Thank you."
    }
}

Below are the two screenshots of what

var section = Configuration.GetSection("ConnectionStrings");

returns

图 1:变量属性

图 2:深入到 JsonConfigurationProvider

A few questions arise.

  1. Why is this returning 3 different JsonConfigurationProviders, one of which includes every setting in the appsettings.json file (shown in Image 2)
  2. Why isn't GetSection("ConnectionStrings") actuall doing just that, returning the sub children of the ConnectionStrings
  3. Given number 2, how do you actually just retrieve the children of ConnectionStrings ?
  4. Assuming a model ConnectionStrings, with one property, List Connections, can the section be converted to an object?

according to this post

https://github.com/aspnet/Configuration/issues/716

  1. the GetSection("Name").Value will return null, you must use GetChildren to get the child items
  2. Bind will populate the properties aginst the provided object , by default it maps against public properties, look at the update to support private properties.
  3. try Get<T>() over bind, it will provide you a strongly typed instance of the configuration object

try a simple POCO of your class (no complex getter/setters, all public, no methods) and then take it from there

Update:
From .net core 2.1 BindNonPublicProperties added to BinderOptions , so if set to true (default is false) the binder will attempt to set all non read-only properties.

var yourPoco = new PocoClass();
Configuration.GetSection("SectionName").Bind(yourPoco, c => c.BindNonPublicProperties = true)

If you use GetSections() along with Bind() you should be able to create poco objects for your use.

var poco= new PocoClass();
Configuration.GetSection("SmsSettings").Bind(poco);

This should return to you a poco object with all the values set.

I understand the answer has been accepted. However, providing proper example code, just in case anyone looking to understand a bit more...

It is quite straight forward to bind custom strong type configuration. ie. configuration json looks like below

{
  "AppSettings": {
    "v": true,
    "SmsSettings": {
      "FromPhone": "9145670987",
      "StartMessagePart": "Dear user, You have requested info from us on starting",
      "EndMessagePart": "Thank you."
    },
    "Auth2Keys": {
      "Google": {
        "ClientId": "",
        "ClientSecret": ""
      },
      "Microsoft": {
        "ClientId": "",
        "ClientSecret": ""
      },
      "JWT": {
        "SecretKey": "",
        "Issuer": ""
      }
    }
  }
}

and your C# classes looks like

public class SmsSettings{
    public string FromPhone { get; set;}
    public string StartMessagePart { get; set;}
    public string EndMessagePart { get; set;}
}

public class ClientSecretKeys
{
    public string ClientId { get; set; }
    public string ClientSecret { get; set; }
}

public class JWTKeys
{
    public string SecretKey { get; set; }
    public string Issuer { get; set; }
}

public class Auth2Keys
{
    public ClientSecretKeys Google { get; set; }
    public ClientSecretKeys Microsoft { get; set; }
    public JWTKeys JWT { get; set; }
}

You can get the section by GetSection("sectionNameWithPath") and then Convert to strong type by calling Get<T>() ;

var smsSettings = Configuration.GetSection("AppSettings:SmsSettings").Get<SmsSettings>();
var auth2Keys= Configuration.GetSection("AppSettings:Auth2Keys").Get<Auth2Keys>();

For simple string values

var isDebugMode = Configuration.GetValue("AppSettings:IsDebugMode");

Hope this helps...

If you use the Bind method on the object returned by GetSection, then this would bind the key value pairs within the section to corresponding properties of the object it has been bound too.

For example,

class ConnectionStrings {
  public string DefaultConnection { get; set;}
  public string ProductionConnection {get; set;}
}

..

var connectionStrings = new ConnectionStrings();
var section = Configuration.GetSection("ConnectionStrings").Bind(connectionStrings);

It works for me on .Net Core directly on Razor HTML:

@Html.Raw(Configuration.GetSection("ConnectionStrings")["DefaultConnectoin"]) <!-- 2 levels -->
@Html.Raw(Configuration.GetSection("Logging")["LogLevel:Default"]) <!-- 3 levels -->
@Html.Raw(Configuration.GetSection("SmsSettings")["EndMessagePart"]) <!-- 2 levels -->

Reference: https://www.red-gate.com/simple-talk/dotnet/net-development/asp-net-core-3-0-configuration-factsheet/

If you required any section with "GetSection" and (key,value), try this:

Configuration.GetSection("sectionName").GetChildren().ToList()

and get a Collection of keys with vallues, can manipulate with LinQ

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