Joydip Kanjilal
Contributor

How to use configuration providers in ASP.Net Core

how-to
Oct 08, 20185 mins
C#Microsoft .NETSoftware Development

Take advantage of configuration providers and dependency injection to configure your ASP.Net Core applications in a loosely coupled manner

Microsoft’s ASP.Net Core is an open-source, cross-platform, lean, and modular framework for building high-performance, scalable web applications. Configuration data in ASP.Net Core is stored as key-value pairs, and can be organized in a multi-level manner. In this article, we will create a new ASP.Net Core project and then use this project to examine how we can work with configuration data in an ASP.Net Core application.

Create a new ASP.Net Core project

To create a new ASP.Net Core project, follow the steps outlined below. Note that this post assumes that you have Visual Studio 2017 installed in your system.

  1. Open Visual Studio 2017 IDE.
  2. Click on File > New > Project.
  3. Select “ASP.Net Core Web Application (.Net Core)” from the list of the templates.
  4. Specify a name for the project.
  5. Click OK.
  6. Select “API” in the “New .Net Core Web Application…” window.
  7. Select the version of ASP.Net Core you would like to use from the drop-down list at the top.
  8. Uncheck the “Enable Docker Support” and “Configure for HTTPS” options. 
  9. Select “No Authentication” as we won’t be using it either.
  10. Click OK.

A new ASP.Net Core project will be created. Note that when a new ASP.Net Core project is created, two files — namely, appsettings.json and appsettings.Development.json — will be configured. Another point to note here is that beginning with ASP.Net Core 2.0, configuration data can now be configured in Program.cs. You are no longer constrained to specify configuration data only in the Startup.cs file. Here is how your Program.cs file will look in ASP.Net Core 2.1:

public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }
        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }

Use the JSON configuration provider in ASP.Net Core

You can leverage the appsettings.json file to store your configuration data, i.e., your database connection strings or application specific settings. The following code snippet illustrates how you can add the appsettings.json file using the AddJsonFile method of the IConfigurationBuilder instance.

 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
         WebHost.CreateDefaultBuilder(args)
             .ConfigureAppConfiguration((hostingContext, config) =>
             {
                 var env = hostingContext.HostingEnvironment;
                 config.SetBasePath(env.ContentRootPath);
                 config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
             })
             .UseStartup<Startup>();

Now, suppose you have the following content in your appsettings.json file.

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "CustomKeys": {
    "KeyA": "ValueA",
    "KeyB": "ValueB"
  }
}

To read values from a configuration file, you need an instance of type IConfiguration. So, if you would like to retrieve the data from the key-value pair of the appsettings.json file in your controller, you should take advantage of dependency injection to inject the IConfiguration instance as shown below.

 public class ValuesController : ControllerBase
    {
        IConfiguration _configuration;
        public ValuesController(IConfiguration configuration)
        {
            _configuration = configuration;
        }
         //Other methods
     }

The following code snippet illustrates how you can leverage the IConfiguration instance to read key-value pair data from the CustomKeys section of the appsettings.json file.

 [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            var keyA = _configuration["CustomKeys:KeyA"];
            var keyB = _configuration["CustomKeys:KeyB"];
            return new string[] { keyA, keyB };
        }

Here is the complete listing of the ValuesController class for your reference.

public class ValuesController : ControllerBase
    {
        IConfiguration _configuration;
        public ValuesController(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            var keyA = _configuration["CustomKeys:KeyA"];
            var keyB = _configuration["CustomKeys:KeyB"];
            return new string[] { keyA, keyB };
        }
    }

You can also create an additional JSON file to store key-value pairs to be used by the application. In other words, not all of your configuration data must reside in the default appsettings.json. Assuming that you have created a file named customsettings.json, the following code snippet shows how these two JSON files (our customsettings.json file and the appsettings.json file that is created by default) can be added using the builder instance.

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
         WebHost.CreateDefaultBuilder(args)
             .ConfigureAppConfiguration((hostingContext, config) =>
             {                
                 var env = hostingContext.HostingEnvironment;
                 string pathOfCommonSettingsFile = env.ContentRootPath;
                 config.SetBasePath(env.ContentRootPath);
                 config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
                 config.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
                 config.AddJsonFile(Path.Combine(pathOfCommonSettingsFile, "customsettings.json"), optional: true);
             })
             .UseStartup<Startup>();

Use the memory configuration provider in ASP.Net Core

The memory configuration provider enables you to store and retrieve configuration data without having to use a physical file; the configuration data is stored directly in memory. You can take advantage of the memory provider to store your configuration data as illustrated in the code snippet given below.

            var builder = new ConfigurationBuilder();
            var profileCollection = new Dictionary<string, string>
            {
                {"AuthorProfile:FirstName", "Joydip"},
                {"AuthorProfile:LastName", "Kanjilal"},
                {"AuthorProfile:Address", "Hyderabad, India"}
            };
            builder.AddInMemoryCollection(profileCollection);
            Configuration = builder.Build();

You can then retrieve the configuration data using the IConfiguration instance in your application as shown in the following code snippet.

var firstName = _configuration["Profile:FirstName"];

Note that, contrary to ASP.Net, configuration data in ASP.NET Core applications are not refreshed when the data is changed. However, you can refresh your configuration data in ASP.Net Core in two ways – either by restarting the application or by calling the Reload() method exposed by the IConfigurationRoot interface in the Microsoft.Extensions.Configuration namespace. The Reload() method explicitly reloads the configuration data from the underlying configuration providers.

The IConfigurationBuilder interface contains many extension methods that you can use to work with configuration data residing in JSON, XML, or INI files. As we’ve seen, you can even work with in-memory configurations. 

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author