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

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…

Leave a Comment