Configuration API In ASP.NET Core - Day Eleven

In the previous article of this series, we discussed about the internationalization and globalization concept within .net core applications. Now, in this article, we will discuss different types of configuration processes in ASP.NET Core applications.

If you want to look at the previous articles of thse series, please visit the links given below.

In the previous version of ASP.NET, the configuration mechanism was mainly written either within Global.asax or web.config file. But in ASP.NET Core, these concepts have been deprecated. Actually, ASP.NET Core supports configuration API which provides different ways of configuring any application based on a list of name pair values which can also be read from different types of sources. This name value pair can be grouped into a multi-level hierarchy. The configuration providers are there for,

  1. File Format (.ini, .json and .xml)
  2. Command line arguments
  3. Environment variables
  4. In memory .Net Objects
  5. AN encrypted user store
  6. Custom Providers which we can install or create

Simple configuration using JSON File

We can store our required configuration details as a key value pair data within a JSON file. To retrieve the value from this configuration of JSON files, we can use Configuration Indexer with the corresponding item’s key.

Console.WriteLine($"message = {Configuration["user:fullname"]}");

For reading the JSON file, we need to add the below packages in the package.json file or directly install the packages from NuGet Manager.

  1. Microsoft.Extenstions.Configuration
  2. Microsoft.Extenstions.Configuration.Json

Actually, name value pairs are written to the basic Configuration Providers which are not persisted; in spite of that, we can create a custom provider that saves values. Sometimes, we need different configuration settings for different environment types, like development and production environment. The steps demonstrate how to use two different Configuration Providers for the source.

We created two different JSON files for reading the Environment Configuration Setting.

  1. appConfig.json
  2. appConfig.<EnvironmentName>.json
  3. Also we need to use Environment variable providers.
  1. public class Startup  
  2. {  
  3.    public Startup(IHostingEnvironment env)  
  4.    {  
  5.       var builder = new ConfigurationBuilder()  
  6.       .SetBasePath(env.ContentRootPath)  
  7.       .AddJsonFile("appConfig.json", optional: true, reloadOnChange: true)  
  8.       .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)  
  9.       .AddEnvironmentVariables();  
  10.       Configuration = builder.Build();  
  11.    }  
  12.     ………………………………  
  13. }  

Basically, AddJsonFile() is used to add JSON configuration source to the builder. 

  1. public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, IFileProvider provider, string path, bool optional, bool reloadOnChange)  
appConfig.json
  1. {  
  2.   "fullname""Debasis Saha",  
  3.   "message""Welcome to Asp.Net Core Application",  
  4.   "Country": [  
  5.     {  
  6.       "city""Kolkata",  
  7.       "State""West Bengal"  
  8.     },  
  9.     {"city""Mumbai","State""Maharastra"}  
  10.   ]  
  11. }  
Program.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6. using Microsoft.AspNetCore.Hosting;  
  7. using Microsoft.Extensions.Configuration;  
  8. using System;  
  9. using System.IO;  
  10.   
  11. namespace Prog10_Web_Configuration  
  12. {  
  13.     public class Program  
  14.     {  
  15.         public static IConfigurationRoot configuration { getset; }  
  16.   
  17.         public static void Main(string[] args)  
  18.         {  
  19.             var builder = new ConfigurationBuilder()  
  20.              .SetBasePath(Directory.GetCurrentDirectory())  
  21.             .AddJsonFile("appConfig.json");  
  22.             configuration = builder.Build();  
  23.             Console.WriteLine($"Author Name = {configuration["fullname"]}");  
  24.             Console.WriteLine($"Message = {configuration["message"]}");  
  25.             Console.WriteLine("Country:");  
  26.             Console.Write($"{configuration["Country:0:city"]}, ");  
  27.             Console.WriteLine($"State {configuration["Country:0:State"]}");  
  28.             Console.Write($"{configuration["Country:1:city"]}, ");  
  29.             Console.WriteLine($"State {configuration["Country:1:State"]}");  
  30.         }  
  31.     }  
  32. }  
Startup.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Builder;  
  6. using Microsoft.AspNetCore.Hosting;  
  7. using Microsoft.AspNetCore.Http;  
  8. using Microsoft.Extensions.DependencyInjection;  
  9. using Microsoft.Extensions.Logging;  
  10.   
  11. namespace Prog10_Web_Configuration  
  12. {  
  13.     public class Startup  
  14.     {  
  15.         // This method gets called by the runtime. Use this method to add services to the container.  
  16.         // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940  
  17.         public void ConfigureServices(IServiceCollection services)  
  18.         {  
  19.         }  
  20.   
  21.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  22.         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
  23.         {  
  24.             loggerFactory.AddConsole();  
  25.   
  26.             if (env.IsDevelopment())  
  27.             {  
  28.                 app.UseDeveloperExceptionPage();  
  29.             }  
  30.   
  31.             app.Run(async (context) =>  
  32.             {  
  33.                 await context.Response.WriteAsync("Hello World!");  
  34.             });  
  35.         }  
  36.     }  
  37. }  
Output

 

How to use In-Memory Provider for Configuration

The current version of ASP.NET Core application also supports In-Memory configuration. In this process, the value is directly stored in the code and can be used in other parts of the application as a configuration data. For using this type of configuration provider, we need to add the below package from NuGet Package Manager. 

  • Microsoft.Extensions.Configuration.Binder

Student.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5.   
  6. namespace Prog10_Web_Configuration_InMemory  
  7. {  
  8.     public class Student  
  9.     {  
  10.         public string StudentName { getset; }  
  11.         public int Age { getset; }  
  12.         public string Class { getset; }  
  13.         public int RollNo { getset; }  
  14.     }  
  15. }  
Startup.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Builder;  
  6. using Microsoft.AspNetCore.Hosting;  
  7. using Microsoft.AspNetCore.Http;  
  8. using Microsoft.Extensions.DependencyInjection;  
  9. using Microsoft.Extensions.Logging;  
  10.   
  11. namespace Prog10_Web_Configuration_InMemory  
  12. {  
  13.     public class Startup  
  14.     {  
  15.         // This method gets called by the runtime. Use this method to add services to the container.  
  16.         // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940  
  17.         public void ConfigureServices(IServiceCollection services)  
  18.         {  
  19.         }  
  20.   
  21.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  22.         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
  23.         {  
  24.             loggerFactory.AddConsole();  
  25.   
  26.             if (env.IsDevelopment())  
  27.             {  
  28.                 app.UseDeveloperExceptionPage();  
  29.             }  
  30.   
  31.             app.Run(async (context) =>  
  32.             {  
  33.                 await context.Response.WriteAsync("Hello World!");  
  34.             });  
  35.         }  
  36.     }  
  37. }  
Program.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6. using Microsoft.AspNetCore.Hosting;  
  7. using Microsoft.Extensions.Configuration;  
  8.   
  9. namespace Prog10_Web_Configuration_InMemory  
  10. {  
  11.     public class Program  
  12.     {  
  13.         public static IConfigurationRoot configuration { getset; }  
  14.   
  15.         public static void Main(string[] args = null)  
  16.         {  
  17.             var dict = new Dictionary<stringstring>  
  18.             {  
  19.                 {"Profile:Board""C.B.S.E. Student"},  
  20.                 {"App:Student:StudentName""Robin Sharma"},  
  21.                 {"App:Student:Age""12"},  
  22.                 {"App:Student:Class""Class VI"},  
  23.                 {"App:Student:RollNo""11"}  
  24.             };  
  25.               
  26.             var builder = new ConfigurationBuilder();  
  27.             builder.AddInMemoryCollection(dict);  
  28.             configuration = builder.Build();  
  29.             Console.WriteLine($"Hello {configuration["Profile:Board"]}");  
  30.             var window = new Student();  
  31.             configuration.GetSection("App:Student").Bind(window);  
  32.             Console.WriteLine($"Name {window.StudentName}");  
  33.             Console.WriteLine($"Age {window.Age}");  
  34.         }  
  35.     }  
  36. }  
Output

Up Next
    Ebook Download
    View all
    Learn
    View all