c# – Startup.cs返回错误的环境

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”

最佳答案 当您在web.config中也有安装环境时,通常会发生这种情况.

例如,如果您在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>

在这种情况下,当您尝试在startup.cs中读取env.EnvironmentName时,您将获得Staging

看看这是否有帮助.

点赞