Read Config file in ASP.NET 5



ASP.NET vNext has a new configuration system.

With the new version of ASP.NET more than one file type is supported.

Currently, there are 3 different file types that are supported: Json, Xml and Ini.

For example, we can define connection string in config.json file:

{
    "Data": {
        "DefaultConnection": { 
            "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true"
        }
    }
}

You can also get  settings from Environment Variables.

To read connection string from config.json from any location in your app you need to add a reference to Microsoft.Framework.ConfigurationModel.Json.

Now simple import namespace and use code below to read connection string from config.json:

 

using Microsoft.Framework.ConfigurationModel.Json;

var configuration = new Configuration()
                .AddJsonFile("config.json")
                .AddEnvironmentVariables();

var connectionString = configuration.Get("Data:DefaultConnection:ConnectionString");

 

You can also load configuration from multiple different config files:

 

  var configuration = new Configuration()
                              .AddJsonFile("config.json")
                              .AddIniFile("config.ini")
                              .AddXmlFile("config.xml")
                              .AddEnvironmentVariables();

To use xml files you need to reference Microsoft.Framework.ConfigurationModel.Xml and for Ini Microsoft.Framework.ConfigurationModel.

Supporting multiple config files and reading values from config files has never been easier.

If you like this article don’t forget to subscribe to this blog and make sure you don’t miss new upcoming blog posts.