Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting environment variables in .NET Core 2.0

I am trying to setting up multiple environments in my .NET Core 2.0 application. See my code below.

Configuration file (Launch.JSON)

"configurations": [
    {
        "name": ".NET Core Launch (web)",
        "type": "coreclr",
        "request": "launch",
        "preLaunchTask": "build",
        // If you have changed target frameworks, make sure to update the program path.
        "program": "${workspaceRoot}/my.api/bin/Debug/netcoreapp2.0/my.api.dll",
        "args": [],
        "cwd": "${workspaceRoot}/my.api",
        "stopAtEntry": false,
        "requireExactSource": false,
        "internalConsoleOptions": "openOnSessionStart",
        "launchBrowser": {
            "enabled": true,
            "args": "${auto-detect-url}",
            "windows": {
                "command": "cmd.exe",
                "args": "/C start ${auto-detect-url}"
            },
            "osx": {
                "command": "open"
            },
            "linux": {
                "command": "xdg-open"
            }
        },
        "env": {
            "ASPNETCORE_ENVIRONMENT": "Development"
        },
        "sourceFileMap": {
            "/Views": "${workspaceRoot}/Views"
        }
    },
    {
        "name": ".NET Core Attach",
        "type": "coreclr",
        "request": "attach",
        "processId": "${command:pickProcess}"
    }
]

Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

StartUp.cs

public class Startup
{
    public IContainer ApplicationContainer { get; private set; }
    private IHostingEnvironment HostingEnvironment { get; set; }
    public IConfigurationRoot Configuration { get; }
    private string ConnectionString
    {
        get
        {
            return this.HostingEnvironment.IsDevelopment() ? Configuration.GetConnectionString("DefaultConnection") : Configuration.GetConnectionString("Production");
        }
    }

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.Development.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.Azuredev.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables();

        Configuration = builder.Build();

        this.HostingEnvironment = env;

        System.Console.WriteLine(env.EnvironmentName); // Here it always give me Production.
    }

My issue

I tried to use command line like dotnet run --environment "Development"

So, it should run on Development Environment, but it always runs with Production, (look I have added console.writeline in my startup.cs file)

Now the strange thing is that if I use F5 to Debug then it runs perfectly with the development environment.

like image 332
Bharat Avatar asked Sep 27 '17 10:09

Bharat


People also ask

How do you set environment variables?

On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables. Click New to create a new environment variable.

How do I set environment variables in Visual Studio?

In Visual Studio 2019 right-click your project, choose Properties . In the project properties window, select the Debug tab. Then, under Environment variables change the value of your environment from Development to Production or other environments.

What is environment variable in C#?

The GetEnvironmentVariable(String) method retrieves an environment variable from the environment block of the current process only. It is equivalent to calling the GetEnvironmentVariable(String, EnvironmentVariableTarget) method with a target value of EnvironmentVariableTarget.


2 Answers

You can update your launchsettings.json to include a 'Development' profile and then run:

dotnet run --launch-profile "Development"

For further details on configuration of the launchSettings.json file see Working with multiple environments

Note that the commandName would probably need to be "Project" (I haven't really tried this much). Example launchSettings.json as follows:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:19882/",
      "sslPort": 0
    }
  },
  "profiles": {
    "Development": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
like image 50
SpruceMoose Avatar answered Oct 14 '22 03:10

SpruceMoose


Finally I have done it...

Let’s look at how I achieved this.

  1. I have added all my profile settings in launchSettings.JSON
  2. Program.cs remains same as I added in my question.
  3. Updated startup.cs (see below)
  4. CLI for run it via terminal is also different.

Now first let's see my project structure.

enter image description here

Code in my launchSettings.json

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:40088/",
      "sslPort": 0
    }
  },
  "profiles": {
    "Development": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "Azuredev": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Azuredev"
      }
    }
  }
}

Code in launch.json

{
"version": "0.2.0",
"configurations": [
        {
            "name": ".NET Core Launch (web)",
            "type": "coreclr",
            "request": "launch",
            "preLaunchTask": "build",
            // If you have changed target frameworks, make sure to update the program path.
            "program": "${workspaceRoot}/my.api/bin/Debug/netcoreapp2.0/my.api.dll",
            "args": [],
            "cwd": "${workspaceRoot}/my.api",
            "stopAtEntry": false,
            "requireExactSource": false,
            "internalConsoleOptions": "openOnSessionStart",
            "launchBrowser": {
                "enabled": true,
                "args": "${auto-detect-url}",
                "windows": {
                    "command": "cmd.exe",
                    "args": "/C start ${auto-detect-url}"
                },
                "osx": {
                    "command": "open"
                },
                "linux": {
                    "command": "xdg-open"
                }
            },
            "sourceFileMap": {
                "/Views": "${workspaceRoot}/Views"
            }
        },
        {
            "name": ".NET Core Attach",
            "type": "coreclr",
            "request": "attach",
            "processId": "${command:pickProcess}"
        }
    ]
}

startup.cs

    public IConfigurationRoot Configuration { get; }

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

        Configuration = builder.Build();

        this.HostingEnvironment = env;
    }

After this all changes, my API is working fine with both the F5 debug option as well as CLI terminal.

To launch the application from the command line, use these keywords:

dotnet run --launch-profile "Development"

OR

dotnet run --launch-profile "Azuredev"
like image 45
Bharat Avatar answered Oct 14 '22 03:10

Bharat