Startup.cs返回错误的环境

时间:2016-10-09 14:07:34

标签: c# asp.net-core asp.net-core-mvc .net-core asp.net-core-1.0

Startup类包含

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

    Console.WriteLine($"{env.EnvironmentName.ToString()}");

    if (env.IsDevelopment())
    {
        // For more details on using the user secret store see 
        // https://go.microsoft.com/fwlink/?LinkID=532709
        builder.AddUserSecrets();
    }

    builder.AddEnvironmentVariables();
    Configuration = builder.Build();
}

但env.EnvironmentName.ToString()返回“Production”。

我已经在 launchSettings.json

中将我的ASPNETCORE_ENVIRONMENT设置为“Development”

3 个答案:

答案 0 :(得分:2)

当您在web.config中设置了环境时,通常会发生这种情况。

例如,如果您在Production -

中将环境设置为launchSettings.json
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Production"
      }
    },

web.config中,如果您有其他环境Staging -

<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false">
  <environmentVariables>
    <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" />
  </environmentVariables>
</aspNetCore>

在这种情况下,当您尝试阅读Staging中的env.EnvironmentName

时,您将获得startup.cs

看看这是否有帮助。

答案 1 :(得分:0)

使用powershell命令实现此功能:

$Env:ASPNETCORE_ENVIRONMENT = "Development"

答案 2 :(得分:0)

这可能对某些人有帮助。

我在本地针对发布的文件运行-而不是通过Visual Studio F5运行。通过命令行设置环境变量会将其添加到无效的用户环境变量中。

要使其正常工作,我要做的就是将ASPNETCORE_ENVIRONMENT添加到系统环境变量中。然后,重新启动后,它开始工作。

要获取环境变量: 右键单击“此PC”,然后单击属性。然后是高级系统设置。然后,最后单击按钮“环境变量”。在下一个弹出窗口中,添加到系统变量。

相关问题