Felipe Deveza
Felipe Deveza

Reputation: 1959

Environment variable not changing as I hope

I set the value "Test" to ASPNETCORE_ENVIRONMENT using PowerShell, but when I start my app, it gets the value from launchSettings.json.

[Environment]::SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Test", "Machine")

If I remove the value from launchSettings.json, the value changes to "Production", not to "Test".

What am I doing wrong?

I will deploy it to two different apps on AWS Beanstalk and I will send a script file to change the environment variable.

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

My launchSettings.json

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:60511/",
      "sslPort": 44392
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "myapp",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "MonitoraApi": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "myapp",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:60512"
    }
  }
}

Upvotes: 3

Views: 1160

Answers (2)

Isantipov
Isantipov

Reputation: 20909

This is an expected behavious as per docs:

The environment for local machine development can be set in the Properties\launchSettings.json file of the project. Environment values set in launchSettings.json override values set in the system environment.

So the answer to your question ("What am I doing wrong?") is as follows: you're not supposed to use launchsettings.json in production (so just remove it and ignore from source control or modify deployment script so that it doesn't copy this file). launchsettings.json is a tool to facilitate easy tests on the development machine.

Upvotes: 5

Matheus Lacerda
Matheus Lacerda

Reputation: 6007

I could get the value "Test" by executing your PowerShell command and the following code:

var environment = Environment.GetEnvironmentVariable(
    "ASPNETCORE_ENVIRONMENT",
    EnvironmentVariableTarget.Machine);

Upvotes: 2

Related Questions