.net core 5.0 使用多環境
阿新 • • 發佈:2022-03-23
例如:想區分開發環境和生產環境不同的配置檔案(比如說本地測試資料庫和正式的資料庫等等),這個時候就會根據不同的環境配置不同的檔案,也可以用多個startup來分離不同的環境,這裡只是分離了配置檔案。
當然個人覺得如果在Linux上面部署直接通過docker掛載配置檔案會比較好,這裡只是記錄一下有這種方式可以達到效果
1. 引入需要的配置檔案(新增新建項=》應用設定檔案)
2. Program配置
這裡是根據當前的環境的名稱動態替換了引用的appsettings..json
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { config.Sources.Clear(); var env = hostingContext.HostingEnvironment; config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); config.AddEnvironmentVariables(); if (args != null) { config.AddCommandLine(args); } }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
3. 修改launchSettings.json的ASPNETCORE_ENVIRONMENT來更改除錯時對應不同的環境名稱,到了這步已經可以滿足除錯的需求了
4. 如果需要部署在windows上面,修改打包好的webconfig檔案,新增環境變數
<environmentVariables> <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="test" /> </environmentVariables>