In the previous version of ASP.NET, the configuration mechanism was mainly written either within Global.asax or web.config file. But in ASP.NET Core, these concepts have been deprecated. Actually, ASP.NET Core supports configuration API which provides different ways of configuring any application based on a list of name pair values which can also be read from different types of sources. This name value pair can be grouped into a multi-level hierarchy. The configuration providers are there for,
- File Format (.ini, .json and .xml)
- Command line arguments
- Environment variables
- In memory .Net Objects
- AN encrypted user store
- Custom Providers which we can install or create
Simple configuration using JSON File
We can store our required configuration details as a key value pair data within a JSON file. To retrieve the value from this configuration of JSON files, we can use Configuration Indexer with the corresponding item’s key.
Console.WriteLine($"message = {Configuration["user:fullname"]}");
For reading the JSON file, we need to add the below packages in the package.json file or directly install the packages from NuGet Manager.
- Microsoft.Extenstions.Configuration
- Microsoft.Extenstions.Configuration.Json
Actually, name value pairs are written to the basic Configuration Providers which are not persisted; in spite of that, we can create a custom provider that saves values. Sometimes, we need different configuration settings for different environment types, like development and production environment. The steps demonstrate how to use two different Configuration Providers for the source.
We created two different JSON files for reading the Environment Configuration Setting.
- appConfig.json
- appConfig.<EnvironmentName>.json
- Also we need to use Environment variable providers.
- public class Startup
- {
- public Startup(IHostingEnvironment env)
- {
- var builder = new ConfigurationBuilder()
- .SetBasePath(env.ContentRootPath)
- .AddJsonFile("appConfig.json", optional: true, reloadOnChange: true)
- .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
- .AddEnvironmentVariables();
- Configuration = builder.Build();
- }
- ………………………………
- }
Basically, AddJsonFile() is used to add JSON configuration source to the builder.