Ad

How Can I Use Config.json To Set Environment-specific Variables For A Visual Studio 2015/DNX Project?

- 1 answer

I have a Visual Studio 2015 solution made up of projects targeting DNX framework. I have been working locally but I plan to deploy to Azure environments (dev/test/prod). Naturally, the solution uses different database connection strings and other variables dependent on the environment. In the past I made use of cloud configuration files to set these variables, reading them with the CloudConfigurationManager.

I am given to understand that I need to use a config.json file. I have the following code in my Startup.cs file:

public Startup(IHostingEnvironment env, IApplicationEnvironment app)
{
    Configuration = new ConfigurationBuilder(app.ApplicationBasePath)
        .AddJsonFile("config.json")
        .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables()
        .Build();

    Configuration.Set("ASPNET_ENV", "Development");
}

My config.json file is currently an empty object { }. How do I add variables to this file (syntax?), and how do I access them from code?

Ad

Answer

Note this line in your startup code:

.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true)

This adds an additional JSON config file which is named depending on your environment name. So add a new file to your project called:

config.<environment-name>.json

And set up the details in there, such as:

{
  "AppSettings": {
    "SomeVariable": "Blah"
  },
  "Data": {
    "YourConnectionString": {
      "ConnectionString": "<connection string here>"
    }
  }
}

For reading the configuration, there's a good answer here: Using IConfiguration globally in mvc6

Ad
source: stackoverflow.com
Ad