Configuration in asp.net core
Asp.net Core supports lots of config providers for different sources such as:
- Command-line Configuration Provider
- Environment Variables Configuration Provider
- File Configuration Provider
- XML Configuration Provider
Two important types of configurations ASP.NET Core supports are:
- app configuration defined in appsettings.json
- host configuration provided through Environment variables prefixed with ASPNETCORE_
Reading configuration from appsettings in asp.net core
Configuration data is available in asp.net core application as key value pairs.Important file for storing configuration data is appsettings.json.Following is how values are stored in appsettings.json
{ "section0": { "key0": "value", "key1": "value" }
We can read it as section name followed by key name:
section0:key0
Read in code
We can read the configuration information from appsettings.json using the configuration API as:
Import Configuration API
using Microsoft.Extensions.Configuration;
Declare class variable
private readonly IConfiguration _config;
Inject in the constructor
public Startup(IConfiguration config) { _config = config; }
or
public HomeController(IConfiguration configuration) { _configuration = configuration; }
Access the configuration information using the configuration API as:
Following will return the value.assuming key is at the root level
Configuration["key"]
if key is in a subsection
"sec2": { "key1": "val1" }
Accessing as a strongly typed object
You can use the Configuration.GetValue<T>(key) method for fetching the value from appsettings.json as a strongly typed object:-
var val1 = Configuration.GetValue<int>("key2"); int tot = val1 + 2;
Getting data related to a section
GetSection extracts a configuration subsection with the specified subsection key to access value in a subsection
configuration.GetSection("section2:subsection0");
in a section
configuration.GetSection("section2:subsection0");
Accessing within a subsection
var val1 = Configuration.GetSection("sec2:key1");
if you try to access key as below then you will not get any value.
var val1 = Configuration.GetSection("key1");
To retrieve the configuration value as a specified type
config.GetValue<T>("Key", Default Value);
Leave a Reply