在 .NET Core 2.0 中设置环境变量

Setting environment variables in .NET Core 2.0

我正在尝试在我的 .NET Core 2.0 应用程序中设置多个环境。请参阅下面的代码。

配置文件(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.
    }

我的问题

我尝试使用像 dotnet 运行 --environment "Development"

这样的命令行

因此,它应该 运行 在 开发环境 上,但它总是 运行 与 生产环境 , (看,我在 startup.cs 文件中添加了 console.writeline

现在奇怪的是,如果我使用 F5 进行调试,那么它 运行 与 开发 环境完美结合.

dotnet run --environmentASPNETCORE_ENVIRONMENT 环境变量没有影响,参见 this issue

这里有一个关于如何以多种方式切换环境的详细说明:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments

例如,您可以从命令行 运行 它(在 dotnet run 之前):set ASPNETCORE_ENVIRONMENT=Development

您可以更新 launchsettings.json 以包含 'Development' 个人资料,然后 运行:

dotnet run --launch-profile "Development"

有关 launchSettings.json 文件配置的更多详细信息,请参阅 Working with multiple environments

请注意,commandName 可能需要是 "Project"(我还没有真正尝试过这么多)。例子launchSettings.json如下:

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

我终于做到了...

让我们看看我是如何做到的。

  1. 我已经在 launchSettings.JSON
  2. 中添加了我所有的配置文件设置
  3. Program.cs 与我在问题中添加的内容相同。
  4. 已更新 startup.cs(见下文)
  5. CLI for 运行 它通过终端也不同。

现在先来看看我的项目结构。

我的代码 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"
      }
    }
  }
}

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;
    }

在这一切发生变化之后,我的 API 在 F5 调试选项和 CLI 终端下都可以正常工作。

要从命令行启动应用程序,请使用这些关键字:

dotnet run --launch-profile "Development"

dotnet run --launch-profile "Azuredev"

对于.NET Core 3.1,正好需要添加:

.AddCommandLine(args)

到 Program.cs

中的 ConfigurationBuilder

为了

dotnet run --environment "Development"

开始工作(切换 ASP.NET 核心环境)。

打开电源shell,到达项目位置

首先使用命令设置环境变量

$Env:ASPNETCORE_ENVIRONMENT = "Qa"

运行 电源申请 shell dotnet 运行 --no-launch-profile