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

20
我正在尝试在我的.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 run --environment "Development"

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

现在奇怪的是,如果我使用F5进行调试,那么它就会完美地在开发环境下运行。


1
我创建了一个演示 https://github.com/d668/NetCoreConfigTransform/ ,使用 slow-cheetah 进行 .NET Core 2.2 控制台应用程序 App.config 转换。 - Toolkit
5个回答

17

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

dotnet run --launch-profile "Development"

有关配置launchSettings.json文件的详细信息,请参阅使用多个环境。请注意,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 中,Profile 标签是否属于 env 标签? - Bharat
@Bharat - 它在 launchSettings.json 中而不是 launch.json(在属性文件夹中)。 - SpruceMoose
我相信是这样的。我已经更新了我的答案,包括一个完整的示例launchSettings.json文件。最好参考https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments作为权威指南。 - SpruceMoose
它给我一个错误,类似于“找不到指定的启动配置文件”,并将生产环境命名为环境。 - Bharat
你的 launchSettings.json 文件在哪里?它应该位于 <web 项目>\properties\launchSettings.json。 - SpruceMoose
显示剩余3条评论

7

终于搞定了...

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

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

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

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

或者

dotnet run --launch-profile "Azuredev"

2
太好了,那调试呢?我该如何设置开发环境变量值的默认调试? - saber tabatabaee yazdi
这比SlowCheetah复杂得多。我只需要该死的SMTP设置等,为什么不能更简单呢? - Toolkit
@sabertabatabaeeyazdi 有没有解决那个混乱的方案? - Toolkit

2

2

对于 .NET Core 3.1,需要添加以下内容:

.AddCommandLine(args)

在Program.cs文件中的ConfigurationBuilder中添加以下内容:

对于

dotnet run --environment "Development"

切换 ASP.NET Core 环境的工作方式。


1

打开PowerShell,到达项目位置

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

$Env:ASPNETCORE_ENVIRONMENT = "Qa"

从PowerShell中运行应用程序

dotnet run --no-launch-profile


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接