.net - .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 运行我的站点时,它错误地使用了生产应用程序设置,但是当我使用调试选项时,它使用了正确的开发应用程序设置。
我该如何解决这个问题?
解决方案
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")
//...
推荐阅读
- reactjs - 组件多次重新渲染并重复添加默认用户
- java - 如何在 Java 中构建 FileReader 和 BufferedReader 构造函数?
- r - 从R中Dataframe中的时间差生成绝对时间
- javascript - 如何刷新视图的这一部分并且只显示所需的单选按钮
- amazon-web-services - AWS Application Load Balancer 可通过 IP 地址访问
- vue.js - Vue 不更新 v-for 信息数组
- java - 如何在不同包中测试子项中的公共方法时从抽象父项中模拟或存根受保护的方法
- html - 使用 flex 的响应式导航栏不会折叠
- jquery - Jquery 复选框数组值按数据属性放入唯一 div
- c# - 检查日期是否在日期期间集合之间