Search code examples
c#asp.netvisual-studio-2017environment-variables

VS 2017 ASP.NET Local environment variables


I have an ASP.NET (.NET Framework 4.6.1) application deployed on Azure app service. In the app service container I have defined environment variables and I access them using:

using System;
private string _secret = Environment.GetEnvironmentVariable("SOME_SECRET");

This works perfectly, but when running locally and doing development, I would like to define environment variables that can be accessed using the same design pattern. This link has an example of creating environment variables with an appsetting.json file, but it uses a different design pattern, and you access the variables with the IConfiguration interface.

My goal is to define my environment variables locally so that my app will run the same way it does in prod, without changing all this code just to get environment variables to work locally. Otherwise, I would have to have both design patterns present and some type of switch based on the runtime. Too much bloat for us.

This is trivial in most languages but I can't find a good solution here.


Solution

  • You can use Environment.SetEnvironmentVariable(string newVariableName, string value) to setup the environment variable locally.

    Take a look at the official Microsoft documentation here.