.NET Core Load Environment Specific Custom Config File

Assume that you are working in a company which maintains different environments, like Development, QA, Staging etc. Now, many times, it happens that a portion of the code is working in one environment and the same code is not working in another environment. In this situation, you need to configure the other environment locally and you need to modify each and every configuration, such as - connectionstring, url, directorypath etc. So, in order to make the developer’s life easy, we can maintain the environment specific configurations and load accordingly.

Let’s see step by step how we can use this feature in .NET Core Web API. 

  • Open Visual Studio and create a new project.
  • Select API template and click the OK button. 
.NET Core Load Environment Specific Custom Config File 

Create two different configuration files, i.e., JSON files - development.json and staging.json; both having different parameter values.

development.json

  1. {  
  2.   "Configuration": {  
  3.     "ConnectionString""Server={devservername};Database={dbname};User ID={devuserid};Password={devpassword};"  
  4.   }  
  5. }  

staging.json

  1. {  
  2.   "Configuration": {  
  3.     "ConnectionString""Server={stagingservername};Database={dbname};User ID={staginguserid};Password={stagingpassword};"  
  4.   }  
  5. }  

Generate a model matching with your config files.

  1. namespace EnvironmentSpecificCustomConfig  
  2. {  
  3.     public class Configuration  
  4.     {  
  5.         public string ConnectionString { getset; }  
  6.     }  
  7. }  

In the startup class constructor, we need to add a JSON whose name should be the value of the parameter EnvironmentName which we get through IHostingEnvironment.

Add a Configuration class to the service collection so that we can inject it whenever it’s required.

  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.Extensions.Configuration;  
  4. using Microsoft.Extensions.DependencyInjection;  
  5.   
  6. namespace EnvironmentSpecificCustomConfig  
  7. {  
  8.     public class Startup  
  9.     {  
  10.         public Startup(IConfiguration configuration, IHostingEnvironment env)  
  11.         {  
  12.             var builder = new ConfigurationBuilder()  
  13.               .SetBasePath(env.ContentRootPath)  
  14.               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)  
  15.               .AddJsonFile($"Config/{env.EnvironmentName}.json", optional: false, reloadOnChange: true)  
  16.               .AddEnvironmentVariables();  
  17.             configuration = builder.Build();  
  18.   
  19.             Configuration = configuration;  
  20.         }  
  21.   
  22.         public IConfiguration Configuration { get; }  
  23.   
  24.         // This method gets called by the runtime. Use this method to add services to the container.  
  25.         public void ConfigureServices(IServiceCollection services)  
  26.         {  
  27.             services.AddSingleton(Configuration.GetSection("Configuration").Get<Configuration>());  
  28.   
  29.             services.AddMvc();  
  30.         }  
  31.   
  32.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  33.         public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  34.         {  
  35.             if (env.IsDevelopment())  
  36.             {  
  37.                 app.UseDeveloperExceptionPage();  
  38.             }  
  39.   
  40.             app.UseMvc();  
  41.         }  
  42.     }  
  43. }  

In the ValuesController, inject the Configuration class via constructor

Using that Configuration instance, get the connection string and return it from the GET method of ValuesController.

  1. using Microsoft.AspNetCore.Mvc;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace EnvironmentSpecificCustomConfig.Controllers  
  5. {  
  6.     [Route("api/[controller]")]  
  7.     public class ValuesController : Controller  
  8.     {  
  9.         private Configuration configuration { getset; }  
  10.         public ValuesController(Configuration configuration)  
  11.         {  
  12.             this.configuration = configuration;  
  13.         }  
  14.   
  15.         // GET api/values  
  16.         [HttpGet]  
  17.         public IEnumerable<string> Get()  
  18.         {  
  19.             return new string[] { "ConnectionString", configuration.ConnectionString };  
  20.         }  
  21.   
  22.         // GET api/values/5  
  23.         [HttpGet("{id}")]  
  24.         public string Get(int id)  
  25.         {  
  26.             return "value";  
  27.         }  
  28.   
  29.         // POST api/values  
  30.         [HttpPost]  
  31.         public void Post([FromBody]string value)  
  32.         {  
  33.         }  
  34.   
  35.         // PUT api/values/5  
  36.         [HttpPut("{id}")]  
  37.         public void Put(int id, [FromBody]string value)  
  38.         {  
  39.         }  
  40.   
  41.         // DELETE api/values/5  
  42.         [HttpDelete("{id}")]  
  43.         public void Delete(int id)  
  44.         {  
  45.         }  
  46.     }  
  47. }  

So far, we have added a JSON file with EnviromentName, but the question may arise that where we can set that environment from.

Right-click on the project name and click "Properties".

Select the "Debug" tab and on the right side, you can see Environment Variables.

By default, Development is set for ASPNETCORE_ENVIRONMENT, so there is no need to change it as of now.

.NET Core Load Environment Specific Custom Config File 

Let’s run the application and in the result, you can see connection string having all development related values.

.NET Core Load Environment Specific Custom Config File 

Now again, go to the Project Properties >> Debug tab and change the value from Development to Staging.

.NET Core Load Environment Specific Custom Config File 

Run the application once again. This time, you can see the connection string having Staging related parameter values.

.NET Core Load Environment Specific Custom Config File 

You can download the sample code from here.