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?
This has had a few twists and turns. I've modified this answer to be up to date with ASP.NET Core 2.0 (as of 26/02/2018).
This is mostly taken from the official documentation:
To work with settings in your ASP.NET application, it is recommended that you only instantiate a
Configuration
in your application’sStartup
class. Then, use the Options pattern to access individual settings. Let's say we have anappsettings.json
file that looks like this:And we have a POCO object representing the configuration:
Now we build the configuration in
Startup.cs
:Note that
appsettings.json
will be registered by default in .NET Core 2.0. We can also register anappsettings.{Environment}.json
config file per environment if needed.If we want to inject our configuration to our controllers, we'll need to register it with the runtime. We do so via
Startup.ConfigureServices
:And we inject it like this:
The full
Startup
class:They just keep changing things – having just updated VS and had the whole project bomb, on the road to recovery and the new way looks like this:
I kept missing this line!
For .NET Core 2.0, things have changed a little bit. The startup constructor takes a Configuration object as a parameter, So using the
ConfigurationBuilder
is not required. Here is mine:My POCO is the
StorageOptions
object mentioned at the top:And the configuration is actually a subsection of my
appsettings.json
file, namedAzureStorageConfig
:The only thing I'll add is that, since the constructor has changed, I haven't tested whether something extra needs to be done for it to load
appsettings.<environmentname>.json
as opposed toappsettings.json
.For .NET Core 2.0, you can simply:
Declare your key/value pairs in appsettings.json:
Inject the configuration service in startup.cs, and get the value using the service
In addition to existing answers I'd like to mention that sometimes it might be useful to have extension methods for
IConfiguration
for simplicity's sake.I keep JWT config in appsettings.json so my extension methods class looks as follows:
It saves you a lot of lines and you just write clean and minimal code:
It's also possible to register
IConfiguration
instance as singleton and inject it wherever you need - I use Autofac container here's how you do it:You can do the same with MS Dependency Injection: