【问题标题】:Setting environment variables in .NET Core 2.0在 .NET Core 2.0 中设置环境变量
【发布时间】:2018-03-08 18:30:11
【问题描述】:

我正在尝试在我的 .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}"
    }
]

程序.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 run --environment "Development"

之类的命令行

所以,它应该在 Development Environment 上运行,但它总是在 Production 下运行,(看我在我的startup.cs 文件)

现在奇怪的是,如果我使用 F5 进行调试,那么它可以在 development 环境中完美运行。

【问题讨论】:

标签: c# asp.net-core-2.0


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    您可以更新您的 launchsettings.json 以包含“开发”配置文件,然后运行:

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

    【讨论】:

    • 配置文件标签是否在launch.json中的env标签下?
    • @Bharat - 它在 launchSettings.json 而不是 launch.json(在属性文件夹中)
    • 我相信是的。我已更新我的答案以包含完整的示例 launchSettings.json 文件。最好参考docs.microsoft.com/en-us/aspnet/core/fundamentals/environments作为权威指南
    • 它给了我类似“无法找到指定的启动配置文件”和生产环境名称的错误
    • 您的 launchSettings.json 文件在哪里?它应该是 \properties\launchSettings.json
    【解决方案3】:

    我终于做到了……

    让我们看看我是如何做到这一点的。

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

    现在首先让我们看看我的项目结构。

    我的 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"
    

    【讨论】:

    • 很好,调试怎么样?如何为开发环境变量值设置默认调试。?
    • 这比慢猎豹要复杂得多。我只需要该死的 SMTP 设置等,为什么不能更简单
    • @sabertababaeyazdi 有什么办法解决这个烂摊子吗?
    【解决方案4】:

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

    .AddCommandLine(args)
    

    到 Program.cs 中的 ConfigurationBuilder

    dotnet run --environment "Development"
    

    工作(切换 ASP.NET Core 环境)。

    【讨论】:

      【解决方案5】:

      打开Powershell,到达项目位置

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

      $Env:ASPNETCORE_ENVIRONMENT = "Qa"

      从电源外壳运行应用程序 dotnet run --no-launch-profile

      【讨论】: