Configuring And Reading Application Settings In ASP.NET Core Application

In this blog, I am going to show you the AppSetting configuration in ASP.NET Core Application.

In ASP.NET Core Application, all the Application settings are now located in appsettings.json file instead of app.config/web.config file.

Here is what the default appsettings.json file looks like, though I have also added an AppSettings section, as shown below.

ASP.NET Core

Configure Startup.cs

Write the highlighted line of code given below inside ConfigureServices method of Startup.cs file.

  1. services.Add(ServiceDescriptor.Singleton<IConfiguration>(Configuration));  

 ConfigureServices method gets called by the runtime. Usually this method is to add the Services to the container.

Screenshot for reference is given below.

ASP.NET Core

Now, read the Application settings from appsettings.json file in ASP.NET Core Application's controller, as shown below.

  1. using Microsoft.Extensions.Configuration;  
  2. public class TestController: Controller  
  3. {  
  4.     private IConfiguration m_configuration;  
  5.     string fileSource, fileDestination = "";  
  6.     public TestController(IConfiguration configruation) {  
  7.         Initialize(configruation);  
  8.     }  
  9.     private void Initialize(IConfiguration configruation) {  
  10.         m_configuration = configruation.GetSection("AppSettings");  
  11.         fileSource = m_configuration["FileSource"];  
  12.         fileDestination = m_configuration["FileDestination"];  
  13.     }  
  14.     public string Get() {  
  15.         -- -- -- -- -- -- -  
  16.         -- -- -- -- -- -- -  
  17.         -- -- -- -- -- -- --  
  18.     }  
  19. }