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

时间:2017-09-27 10:01:36

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

我正在尝试在.net core 2.0应用程序中设置Multiple Environment,请参阅下面的代码。

  

配置文件(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 run --environment“Development”

因此,它应该在开发环境上运行,但它始终以生产运行,(看起来我在启动时添加了 console.writeline 的.cs)

现在奇怪的是,如果我使用F5进行调试,那么它与开发环境完美匹配。

6 个答案:

答案 0 :(得分:8)

您可以更新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"
      }
    }
  }
}

答案 1 :(得分:3)

最后我做到了..

让我们看看我是如何实现这一目标的。

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

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

    enter image description here

      我的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&#34; Development&#34;

    OR

      

    dotnet run --launch-profile&#34; Azuredev&#34;

答案 2 :(得分:2)

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

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

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

答案 3 :(得分:2)

您可以在命令终端中使用以下命令设置环境。

setx ASPNETCORE_ENVIRONMENT "Environment_Name"

环境名称可以是开发,分期或生产

请注意,当前打开的窗口中未设置环境变量。您需要打开一个新的命令提示符以查看更新的环境。如果打开管理命令提示符并添加/ M开关,也可以设置系统变量(而不仅仅是用户变量)

For reference

答案 4 :(得分:1)

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

.AddCommandLine(args)

访问Program.cs中的ConfigurationBuilder

dotnet run --environment "Development"

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

答案 5 :(得分:0)

打开Powershell,到达项目位置

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

$Env:ASPNETCORE_ENVIRONMENT = "Qa"

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