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.
Create two different configuration files, i.e., JSON files - development.json and staging.json; both having different parameter values.
development.json
- {
- "Configuration": {
- "ConnectionString": "Server={devservername};Database={dbname};User ID={devuserid};Password={devpassword};"
- }
- }
staging.json
- {
- "Configuration": {
- "ConnectionString": "Server={stagingservername};Database={dbname};User ID={staginguserid};Password={stagingpassword};"
- }
- }
Generate a model matching with your config files.
- namespace EnvironmentSpecificCustomConfig
- {
- public class Configuration
- {
- public string ConnectionString { get; set; }
- }
- }
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.
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
-
- namespace EnvironmentSpecificCustomConfig
- {
- public class Startup
- {
- public Startup(IConfiguration configuration, IHostingEnvironment env)
- {
- var builder = new ConfigurationBuilder()
- .SetBasePath(env.ContentRootPath)
- .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
- .AddJsonFile($"Config/{env.EnvironmentName}.json", optional: false, reloadOnChange: true)
- .AddEnvironmentVariables();
- configuration = builder.Build();
-
- Configuration = configuration;
- }
-
- public IConfiguration Configuration { get; }
-
-
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddSingleton(Configuration.GetSection("Configuration").Get<Configuration>());
-
- services.AddMvc();
- }
-
-
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
-
- app.UseMvc();
- }
- }
- }
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.
- using Microsoft.AspNetCore.Mvc;
- using System.Collections.Generic;
-
- namespace EnvironmentSpecificCustomConfig.Controllers
- {
- [Route("api/[controller]")]
- public class ValuesController : Controller
- {
- private Configuration configuration { get; set; }
- public ValuesController(Configuration configuration)
- {
- this.configuration = configuration;
- }
-
-
- [HttpGet]
- public IEnumerable<string> Get()
- {
- return new string[] { "ConnectionString", configuration.ConnectionString };
- }
-
-
- [HttpGet("{id}")]
- public string Get(int id)
- {
- return "value";
- }
-
-
- [HttpPost]
- public void Post([FromBody]string value)
- {
- }
-
-
- [HttpPut("{id}")]
- public void Put(int id, [FromBody]string value)
- {
- }
-
-
- [HttpDelete("{id}")]
- public void Delete(int id)
- {
- }
- }
- }
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.
Let’s run the application and in the result, you can see connection string having all development related values.
Now again, go to the Project Properties >> Debug tab and change the value from Development to Staging.
Run the application once again. This time, you can see the connection string having Staging related parameter values.
You can download the sample code from here.