Question

I am using .NET Core to build a simple console application. However, I am stuck by not being able to read a few settings from an appsettings.json file. How do I go about doing this?

From what I understand I need access to an ApplicationEnvironment instance and then use a ConfigurationBuilder but where do get these from? I am working with the rc1 bits.

1 Answers

I am answering my own question as I figured it out (for RC1 in this case).

First add these two dependencies to config.json:

"dependencies": {
  "Microsoft.Framework.Configuration": "1.0.0-beta8",
  "Microsoft.Framework.Configuration.Json": "1.0.0-beta8"
}

BTW: It is the second one that I was missing, but this is necessary to read json files.

Next, add the below code and you're ready to go:

var builder = new ConfigurationBuilder()
                     .AddJsonFile("appsettings.json");

var configuration = builder.Build();
var setting = Configuration["someSetting"];

It is best to set configuration as a static or global property.

I hope this helps someone.