Home > Software design >  Why does .net load the prod json values when running via visual studio code?
Why does .net load the prod json values when running via visual studio code?

Time:01-13

I have created a new .net web api project.

There are 2 json settings file - 1 is for dev and other is for prod.

I add key1 to dev json file and add key2 to prod json file.

In my program.cs I have following code:

builder.Configuration["key1"]
builder.Configuration["key2"]

Even though I have run the project via visual studio code, why is it loading the value from the prod json file?

CodePudding user response:

The environment isn't affected by how you run the application. It's determined by checking the DOTNET_ENVIRONMENT or ASPNETCORE_ENVIRONMENT environment variables. You can configure your IDE or editor to set those environment variables to a specific value when starting the project but that's no different than opening a console and setting the environment variables.

This is described in Used multiple environments in ASP.NET Core but actually applies to any .NET Core application that uses either the Generic host.

Different IDEs use different ways to specify debugging profiles and set environment variables when starting an application.

  • In Visual Studio you can specify the environment variables in the Debug Properties page. Those values are stored in the Properties\launchSettings.json file. This is described in Development and launchsettings.json.

  • JetBrains Rider supports both launchSettings.json and its own profiles.

  • Visual Studio Code on the other hand stores launch configurations stored in a launch.json file in the .vscode folder. It can also use launchSettings.json by setting an attribute in launch.json.

The available attributes are described in Launch.json attributes. The env attribute allows specifying environment variables.

The article Configuring launch.json for C# debugging describes how to use that file to start the browser, navigate to a specific URL, set environment variables etc:

"env": {
    "DOTNET_ENVIRONMENT":"Development"
}

The same document shows how to use launchSettings.json in VS Code by setting the launchSettingsProfile attribute.

If you have a Development profile in launchSettings.json:

{
  "profiles": {
    "Development": {
      "commandName": "Project",
      "environmentVariables": {
        "DONTET_ENVIRONMENT":"Development"
      }
    }
  }
}

You can use it in VS Code by specifying launchSettingsProfile in launch.json :

"launchSettingsProfile": "Development"
  •  Tags:  
  • Related