0

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?

3
  • 1
    you dont store data that changes frequently in appsettings Commented May 13, 2019 at 12:29
  • I think you should store your profiles in database Commented May 13, 2019 at 12:50
  • Hello, The data will be static. I said dynamic structure because each profile has different scheme which is changing by Type property. I will edit my question to be clear about it. Commented May 13, 2019 at 13:19

1 Answer 1

2
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"]);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Alexandr. I got your idea and it works. I changed a little bit to succeed what i need. My final code is like that: var _profilesArray = _profiles.Select(p => new { Key = p.Key, Type = p["Type"] });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.