JumpStart # 46 – Environment Variables in ASP.Net Core MVC Application

In this jumpstart we are going to see how to set Environment variables in ASP.Net Core MVC application. This is new feature in ASP.Net Core and primarily used for configuring the behavior across multiple environments likes Development, Staging and Production. We can also add extra environment variables and access them in application using IConfigurationRoot.

NOTE: Updated this tutorial on 2/26/2017 with MSBuild based Dotnet SDK.

Create an ASP.Net Core Application using VS 2017. I am using following version of Dotnet SDK which is based on MSBuild/CSProj (remember that previous versions of ASP.Net Core are based on Project.json/XProj.).

 image

Now open Properties from the solution explorer.

image

Lets add a new Environment Variable, by clicking on Add option.

image

We can also add environment variables to profiles in launchSettings.json.

"IIS Express": {
  "commandName": "IISExpress",
  "launchBrowser": true,
  "environmentVariables": {
    "TestKey": "TestValue",
    "ASPNETCORE_ENVIRONMENT": "Development"
  }
}

To know which environment has been configured, we have following IHostingEnvironment extension methods. IHostingEnvironment is available through out the application and can be injected into any controller or view.

env.IsDevelopment()
env.IsStaging()
env.IsProduction()

We can also use env.IsEnvironment(string name) to check the environment by passing environment name as input (for example “Development” etc.,). Remember environment variables are case insensitive.

To access other environment variables, we do not have extension methods in IHostingEnvironment. We will use IConfigurationRoot to access other variables. To use IConfigurationRoot (root configuration and inherited by IConfiguration), we need to add it as a service to application. Create an IConfigurationRoot public property, initialize it in Startup class constructor (especially add environment variables to configuration root using AddEnvironmentVariables() method) and finally inject it as Singleton service in ConfigureServices method.

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();

    if (env.IsDevelopment())
    {
        builder.AddApplicationInsightsSettings(developerMode: true);
    }
    Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IConfigurationRoot>(Configuration);
    services.AddMvc();
}

Now inject IConfigurationRoot into the HomeController and use it in Index action (which will simply read our newly added environment variable and send it back in JSON response).

private IConfigurationRoot _config;
public HomeController(IConfigurationRoot config)
{
    _config = config;
}

public IActionResult Index()
{
    var envVariable = _config["TestKey"];
    return Json(envVariable);
}

When we test the application using postman tool, we will have following output.

image

That’s it for now. Happy Coding and Stay Tuned!!!

You may also like...