首页 > 解决方案 > .NET 5.0 未在开发中使用正确的环境

问题描述

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

例如:

appsettings.开发:

"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 运行我的站点时,它错误地使用了生产应用程序设置,但是当我使用调试选项时,它使用了正确的开发应用程序设置。

我该如何解决这个问题?

标签: .netentity-frameworkasp.net-core

解决方案


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文件,您还可以通过调用UseEnvironment()IHostBuilder 上的方法(在 Program.cs 文件中)来设置环境:

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

参考:Development 和 launchSettings.jsonUseEnvironment


推荐阅读