Blog Archives

Access configuration with .Net Core

.Net Core is an open source framework developed on github. For those who are new to it, .Net core is a paradigm shift from the previous release (in a good way). It is an implementation of OWIN (Open web interface for Net).

In previous frameworks, we had appsettings.config file (i.e. for console app) where we configure various key value pairs apart from some project specific settings. In .Net Core (2.0) console App, we don’t get .config file by default.

Below steps will help you reading the config values from config files in .Net Core.

Reading AppSettings using previous System.Configuration.ConfigurationManager class

ConfigurationManager.AppSetting[“key”]

This won’t work in .Net Core as System.Configuration is not present for Core yet (till Core 2.0). You need to do as per below.

  • Create a Console App with .Net Core 2.0
  • Create a appsettings.json file and add to the root of the project.
  • Add desired key value settings in this file.

{
“docDbSettings”: {
“EndpointUrl”: “https://localhost/443”,
“AuthKey”: “134KJKJSHDKFJL###LKJSLKFGK;E 12934903459-          @@@0983459+==”,
“DatabaseId”: “ToDoList”,
“CollectionId”: “Items”
}
}

  • Right click on this json file and select “Copy To Output directory” to “copy always” . This will ensure that file is present in client under ‘bin\Debug\netcoreapp2.0’.
  • Install the below nuget packages
    • Microsoft.Extensions.Configuration
    • Microsoft.Extensions.Configuration.FileExtensions
    • Microsoft.Extensions.Configuration.Json
  • Below is the code to set upConfigurationBuilder which is equivalent to previous ConfigurationManager class to read the keys.
private static IConfiguration Configuration;

static void Main(string[] args)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json");

    Configuration = builder.Build();

    // read the keys
    var Endpoint = Configuration["docDbSettings:EndpointUrl"]?.ToString(); 
    var Key = Configuration["docDbSettings:AuthKey"]?.ToString();
    var DatabaseId = Configuration["docDbSettings:DatabaseId"]?.ToString();
    var CollectionId = Configuration["docDbSettings:CollectionId"]?.ToString();  
}
  • You can notice the tags traversal supported withing json structure. It even supports accessing the keys with index like [“superadmins[0]:Name”] if  it is an array of array like the below

{

“superadmins”: [
{
“Name”: “XYZ”,
“email”: “abc@text.com”
},
{
“Name”: “XYZ”,
“email”: “abc@text.com”
}

]

}

You can get more details from Microsoft documentation on here

You can also read an excellent article from Scott Hanselman on how to secure the config file having connection strings and other keys better in cloud and CI-CD ready development world.

 

Hope it helps!

 

Advertisements