Kerim Doruk Akıncı
Kerim Doruk Akıncı

Reputation: 392

Getting Key-Value from Dynamic JSON Structure Scheme in asp.net core2 application

I'm searching a proper way to read my appsettings.json file in asp.net core 2 application. I'm sharing my appsettings file.

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "Profiles": {
    "PROFILE1": {
      "Type": "AWS AssumeRole Credential",
      "RoleArn": "arn:aws:iam::11111111111111:role/CrossRole"
    },
    "PROFILE2": {
      "Type": "AWS InstanceProfile Credential",
      "RoleArn": "arn:aws:iam::000000000000:role/Role"
    },
    "AWS_DEBUG": {
      "Type": "AWS Credential MOCK",
      "MockProfile": "PROFILE1",
      "AccessKey": "xxxxxxxxxxxxxxxxxxxxxxxxxx",
      "SecretKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
    }
  }
}

The problem is that i want to retrieve all of the profile names and later then i will look at their "Type" property and will understand what other properties it has to be. So i can manage this dynamic json structure scheme in my code base.

My Web Application Startup script is setting configurations with IConfiguration object and I'm using it to access the json.

       public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

I could use configuration["Profiles:PROFILE_SCHEME_1:Type"] to retrieve the values but i want to get these profile names, so the user can change the profile names without a problem. Is there a way to do "foreach profileName in ProfilesSection) and after then i have to retrieve that section to process. what is the best approach for that?

Upvotes: 0

Views: 1009

Answers (1)

svstnv
svstnv

Reputation: 233

var profiles = Configuration.GetSection("Profiles").GetChildren();

And then, for example, we can obtain the keys:

var profilesKeys = profiles.Select(p=>p.Key);

The types of the profiles you can obtain as follows:

var profilesTypes = profiles.Select(p => p["Type"]);

Upvotes: 2

Related Questions