Load Configuration (.INI , .JSON, .XML) in ASP.NET Core

Loading Configuration INIJSONXML in ASPNET Core

In this article, we will see how to Load Configuration (.INI,.JSON,.XML) in ASP.NET Core.

Now with expanded support to applications like Windows Form and WPF in .NET Core Core ecosystem, It is very much possible that you might need to use your traditional config file system like XML, JSON or INI file etc.

The good news is that you can read all the above file systems using the File Provider available in the .NET Core ecosystem.

Today in this article, we will cover below aspects,

If you are interested to load configuration in .NET Core using dependency injection(DI), I have talked about how to load key-value pairs via dependency injection using IConfiguration and IOption interface.

So let’s get started with the ASP.NET Core application example,

Loading appsettings.json

Loading of appsettings.json support is provided out of the box in ASP.NET Core-based application. That means you don’t really need to write a single line of code to load these details.

As we discussed in our last article CreateDefaultBuilder () method helps to load configuration details provided in appsettings.json or appsettings.{env.EnvironmentName}.json by default.

This is available by default in the ASP.Net Core WebAPI template.

Config details are available by IConfiguration and IOption interfaces.

Load configuration from a file like JSON INI or XML

Configuration – Loading INI File

ASP.NET Core provides INI Configuration Provider which loads configuration from INI file key-value pairs at runtime.

To use INI file configuration at runtime, call the AddIniFile extension method on an instance of ConfigurationBuilder as shown below,

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                 .ConfigureAppConfiguration((hostingContext, config) =>
                 {
                    
                  config.AddIniFile("config.ini", optional: false, 
                  reloadOnChange: false);

                 })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

Here is a sample .ini file,

[section0]
key0=value
key1=value

[section1]
subsection:key=value

[section2:subsection0]
key=value

[section2:subsection1]
key=value
blank

Let’s not look at how to load configuration details available in JSON files

Configuration – Loading custom JSON file

If you want to load a custom JSON file (apart from apsetting.json), ASP.NET Core provides JSON Configuration Provider(which also loads apsetting.json).

To use custom JSON configuration at runtime, call the AddJsonFile extension method on an instance of ConfigurationBuilder as shown below,

Example

 public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                 .ConfigureAppConfiguration((hostingContext, config) =>
                 {

                   config.AddJsonFile(
                   "config.json", optional: false, reloadOnChange: false);

                 })

                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

Sample custom JSON file as below,

{
  "ProducerConfig": {
    "Key1": "true",
    "Key2": "false"
  }

}
blank

Configuration – Loading XML File

If you want to load an XML file ASP.NET Core provides XML Configuration Provider. To use XML configuration at the runtime, Please call AddXmlFile extension method on an instance of ConfigurationBuilder as shown below,

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                 .ConfigureAppConfiguration((hostingContext, config) =>
                 {

                  config.AddXmlFile(
                  "config.xml", optional: false, reloadOnChange: false);

                 })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

Sample custom XML file as below,

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <DataBase>
    <key0>value</key0>
    <key1>value</key1>
  </DataBase>
  <Application>
    <key0>value</key0>
    <key1>value</key1>
  </Application>
</configuration>

blank

In all of the above discussed FileConfigurationProvider, related the extension methods like AddJsonfile() or AddIniFile() or AddXmlFile lets you specify parameters like If the file is optional or not, also if the option to specify reload is required or not.

Interfaces for Configuration DI

IConfiguration and IOption are very helpful interfaces for doing dependency injection of your primitive types often available in the form of key-value pairs through the configuration files.

Once you load this configuration from different sources, the next important aspect is how to inject these configurations in the required component so that it can be used as and when needed.

Strongly Typed Configuration

I have talked about how to load key-value pairs via dependency injection (DI) using IConfiguration and IOption interface as below,

Using Configuration Builder a Non-DI Approach

You can load any configuration like apsettings.json or .ini or XML or, etc using a simple approach without dependency injection(DI).

Please see the below article for more details.

The same above technique on configuration can be used in Console, Windows Forms or WPF applications as well. I shall very soon put an article on the same. Stay tuned..!!

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!

Summary

Today in this article, we learned in .NET Core how seamlessly one can load configuration from different file providers like JSON, INI, or XML files. We understood that by using these File configuration providers, we can very much load configuration from all types of files. This configuration gives developers and administrators of applications a proper way to consume/use the required resources in their applications.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



10 thoughts on “Load Configuration (.INI,.JSON,.XML) in ASP.NET Core

    1. Hi Edo,

      Thanks for the query. You may want to use Configuration Builder to load the ini or json file name stored in apsetting.json.

      [cc lang=”csharp”]
      .ConfigureAppConfiguration((hostingContext, config) =>
      {
      var builtConfig = new ConfigurationBuilder()
      .AddJsonFile(“appsettings.json”)
      .AddCommandLine(args)
      .Build();

      config.AddIniFile(builtConfig.GetSection(“ConfigName”).Value, optional: false, reloadOnChange: false);
      ..
      }
      [/cc]

      Hope this helps.

      1. oh thanks
        yes, we still cannot uses default appsettings … so we have to build it ourown

        ok i’ll try it

        thanks

      2. Yes, Edo.
        I found the default setting(apsettings.json) will be available in the pipeline post Startup class gets invoked ([cc lang=”csharp”]UseStartup[/cc]) using generic Host Builder CreateDefaultBuilder. Such default setting are avaialbe using IConfiguration interface easily in any part of your code.

        However, if you need to load something before StartUp then above way we can very much load the configuration.

        Have a good weekend! Please do subscribe to mail notification for any future updates.

        Thanks

      3. Many thanks … the above code is a the solution for my problem
        i’m new to .net core
        and without many documentation available, sometime i get a stumbling block without knowing how to remove it.

Leave a Reply

Your email address will not be published. Required fields are marked *