How Can I Automatically Configure Appsettings.json For Both Dev And Release Environments In ASP.NET Core Using C#?

In ASP.NET Core, you can automatically set the appsettings.json file based on the environment in which the application is running. This allows you to separate your application configurations for different environments, such as development, testing, and production.

Here are the steps to achieve this:

  1. Create separate appsettings.json files for each environment you want to support. For example, you can have appsettings.Development.json, appsettings.Production.json, etc. Each file should contain the configuration settings specific to that environment.

  2. In the Startup.cs file, configure the application to use the appropriate configuration file based on the current environment by using the ConfigurationBuilder class. Add the following code inside the ConfigureServices method:

public Startup(IConfiguration configuration, IWebHostEnvironment env)
    Configuration = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)

public IConfiguration Configuration { get; }

This code loads appsettings.json followed by the environment-specific JSON file (e.g., appsettings.Development.json), based on the current environment name.

  1. In the ConfigureServices method, replace services.AddMvc() with services.AddControllers(). This is required for later versions of ASP.NET Core (e.g., 3.0 onwards).

  2. Update the Configure method to use the appsettings.json configuration. Replace app.UseMvc() with app.UseRouting().UseEndpoints(endpoints => { endpoints.MapControllers(); });.

Note: Make sure you have the Microsoft.Extensions.Configuration package installed. You can do this by adding the following NuGet package to your project: Microsoft.Extensions.Configuration.

Now, when running the application in different environments, the appropriate appsettings.{environment}.json file will be automatically loaded.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!