I have setup my AppSettings data in appsettings/Config .json like this:
{
"AppSettings": {
"token": "1234"
}
}
I have searched online on how to read AppSettings values from .json file, but I could not get anything useful.
I tried:
var configuration = new Configuration();
var appSettings = configuration.Get("AppSettings"); // null
var token = configuration.Get("token"); // null
I know with ASP.NET 4.0 you can do this:
System.Configuration.ConfigurationManager.AppSettings["token"];
But how do I do this in ASP.NET Core?
First off: The assembly name and namespace of Microsoft.Framework.ConfigurationModel has changed to Microsoft.Framework.Configuration. So you should use: e.g.
as a dependency in
project.json
. Use beta5 or 6 if you don't have 7 installed. Then you can do something like this inStartup.cs
.If you then want to retrieve a variable from the config.json you can get it right away using:
or you can create a class called AppSettings like this:
and configure the services like this:
and then access it through e.g. a controller like this:
So I doubt this is good practice but it's working locally, I'll update this if it fails when I publish/deploy (to an IIS web service).
Step 1.) Add this assembly to the top of your class (in my case, controller class):
using Microsoft.Extensions.Configuration;
Step 2.) Add this or something like it:
var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json").Build();
Step 3.) Call your key's value by doing this (returns string):
config["NameOfYourKey"]
Just to complement the Yuval Itzchakov answer.
You can load configuration without builder function, you can just inject it.
If you just want to get the value of the token then use
Configuration["AppSettings:token"]
Was this "cheating"? I just made my Configuration in the Startup class static, and then I can access it from anywhere else:
Following works for Console Apps;
1- install following
nuget
packages (.csproj
);2- Create
appsettings.json
at root level. Right click on it and "Copy to Output Directory" as "Copy if newer".3- Sample config file:
4- Program.cs
configurationSection.Key
andconfigurationSection.Value
will have config properties.