Environment variables in ASP.Net Core API

Today while playing with an web API to send emails I decided I needed to once and for all figure out how to retrieve environment variables and use them in my web API’s.  Prior to this I had always hacked out something else but on this API I wanted to be able to set up mail server as environment variable.

Seemed like such an easy task, in C# programs you just import the System.Environment name space then use:

myVariable = GetEnvironmentVariable(“name”);

It was not quite so easy in ASP.Net Core web application.

First, I found out my application was already configuring five providers:

  • Extensions.Configuration.ChainedConfigurationProvider
  • JsonConfigurationProvider
  • JsonConfigurationProvider
  • EnvironmentVariablesConfigurationProvider
  • CommandLineConfigurationProvider

Which was great because I needed to use EnvironmentVariablesConfigurationProvider to get the environment variables.

However, this was in a provider in the configuration and I was not at all sure how to get it into the service that needed to use it, or how to get the environment variables out.

After much playing around and searching I figured out I could just inject IConfiguration into the constructor of my service.  So I had:

public MyService(IConfiguration configuration) 
{ 
    localConfiguation = configuration; 
}

But I still needed to get at the environment variable, which I could see in the debugger but not figure out how to access. 

I finally stumbled on to this article ASP.NET Core - Accessing Configuration Settings and while it did not apply to what I was trying to do (I already knew how to get settings from appsettings.json). The article did have some code that led me to the solution.

var dashboardTitle = configuration["DashboardSettings:Title"];   var isSearchBoxEnabled = configuration["DashboardSettings:Header:IsSearchBoxEnabled"];   var headerBannerTitle = configuration["DashboardSettings:Header:BannerTitle"];   var isBannerSliderEnabled = configuration["DashboardSettings:Header:IsBannerSliderEnabled"];  

 

This made me think what if I just try localConfiguration[“environmentVariable”]?

It worked great!

Now in the windows shell I can set globally:

set MailServer = my.mailsever.com

Then in the code:

string MailServerName = configuration["MailServer"];

Add comment