【问题标题】:.NET 5.0 not using correct environment in Development.NET 5.0 未在开发中使用正确的环境
【发布时间】:2021-08-14 06:31:35
【问题描述】:

我有一个 .NET 5.0 应用程序,我根据环境使用不同的 appsettings 文件,以便为我的 SQL 数据库提供不同的连接字符串。

例如:

appsettings.Development:

"ConnectionStrings": {
    "DefaultConnection": "Server=<development server connection string>"
},

appsettings.Production:

"ConnectionStrings": {
    "DefaultConnection": "Server=<production server connection string>"
},

在我的 startup.cs 中:

var builder = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
    .AddEnvironmentVariables();

我在 Mac 上使用 vscode。当我使用 dotnet run 运行我的网站时,它错误地使用了生产 appsettings,但是当我使用 Debug 选项时,它使用了正确的 Development appsettings。

我该如何解决这个问题?

【问题讨论】:

  • 查看项目中launchSettings.json 文件中的变量ASPNETCORE_ENVIRONMENT
  • 这就是问题所在,我没有launchsettings.json。我以为我可以将环境变量添加到 launch.json 但事实证明我也需要 launchsettings.json

标签: .net entity-framework asp.net-core


【解决方案1】:

可以,可以在项目的Properties\launchSettings.json文件中设置本地机开发环境。 launchSettings.json 中设置的环境值会覆盖系统环境中设置的值。

查看以下示例代码,在launchSettings.json中,我们可以通过ASPNETCORE_ENVIRONMENT设置环境值:

{
  "iisSettings": {
    "windowsAuthentication": false, 
    "anonymousAuthentication": true, 
    "iisExpress": {
      "applicationUrl": "http://localhost:64645",
      "sslPort": 44366
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "EnvironmentsSample": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

此外,如果没有launchSettings.json 文件,您还可以通过调用IHostBuilder 上的UseEnvironment() 方法(在Program.cs 文件中)来设置环境:

Host.CreateDefaultBuilder(args)
    .UseEnvironment("Development")
    //...

参考:Development and launchSettings.jsonUseEnvironment

【讨论】:

    猜你喜欢
    • 2011-09-28
    • 2011-03-04
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    • 2010-11-29
    • 2011-06-02
    • 2021-07-15
    相关资源
    最近更新 更多