Home > OS >  Visual Studio 2022 System.Environment.GetEnvironmentVariable not working
Visual Studio 2022 System.Environment.GetEnvironmentVariable not working

Time:09-21

I know this is still in preview, but I just want to make sure I am not doing anything wrong as I have done things like this in the past. I have my Environment variables set in properties: enter image description here

And I am trying to set up my tests:

[TestInitialize]
public void Initialize()
{
    var test = Environment.GetEnvironmentVariables();
    // test enumerates all the Env variables, don't see it there
    var connectionString = Environment.GetEnvironmentVariable("CONNECTION_STRING");
    if (string.IsNullOrWhiteSpace(connectionString)) // so this is obviously null
        throw new ArgumentNullException("CONNECTION_STRING");
    _ConnectionString = connectionString;
}

As you can see by my comments, the environment variables are not found/loaded.

What am I missing? Thank you.

CodePudding user response:

I'm assuming that you are using Visual Studio 2022 because you are using .NET 6 and the minimal host (i.e., no Startup.cs)?

The general preference is not to store information in the Environment Variables given that this information is often uploaded to GitHub and can be trawled and used against you.

For a local development secret, the preference is to store these using the secrets.json file. There is information on how to do this at Safe Storage of Secrets, as well as details on accessing Configuration files at Accessing Configuration File Information.

For the TL;DR: Crowd the steps below might help (this is what I did in my Blazor app with .NET 6):

  1. In Visual Studio 2022, right click on the project in question and select 'Manage User Secrets'. This will create a local secrets.json file and open it. It will also add a GUID in your project tile for UserSecretsId.
  2. Create your secrets as JSON key value pairs in this file as you would for environment variables.
  3. Go to 'Connected Services' in your project and configure the Secrets.json service.
  4. Add the 'User Secrets' to your configuration file; this will depend on exactly where this is happening.
  5. Inject the IConfiguration into your controller and save this to a field.
  6. Call the data you want using:
    {yourConfigurationFieldName}.GetValue<string>({yourJsonKey})
    
  • Related