在進行項目開發時,經常要求開發環境,測試環境及正式環境的分離,而且不一樣環境運行的參數都是不同的,好比監聽地址,數據庫鏈接信息等。固然咱們把配置信息保存到一個文件中,每次發佈的時候,能夠先修改配置文件的內容,而後再進行程序發佈,這樣操做起來無疑是很麻煩,每次發佈都得先肯定對應的環境,而後修改配置信息,若是須要同時發佈多個環境版本,那就得進行屢次操做。數據庫
在執行dotnet run以前,能夠先執行如下下面的指令:json
set ASPNETCORE_ENVIRONMENT= 環境名稱,注意這裏沒有引號,直接把環境名稱寫成具體的值便可,好比 set ASPNETCORE_ENVIRONMNET=development,而後再執行dotnet run指令,這樣當前運行就會按照set指令中設置的環境進行運行。windows
public IConfiguration Configuration { get; } public Startup(IHostingEnvironment env) { Console.WriteLine(env.EnvironmentName); var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); }
項目中有2個appsettings.jsonapp
namespace AuthorityManagement { using System.IO; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; public static class Program { public static void Main(string[] args) { var config = new ConfigurationBuilder() .AddEnvironmentVariables() .AddCommandLine(args) .SetBasePath(Directory.GetCurrentDirectory()) .Build(); var host = new WebHostBuilder() .UseEnvironment(config["ASPNETCORE_ENVIRONMENT"]) .UseConfiguration(config) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .UseApplicationInsights() .Build(); host.Run(); } } }
{ "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:32030/", "sslPort": 0 } }, "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "dev" } }, "AuthorityManagement": { "commandName": "Project", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "dev" }, "applicationUrl": "http://localhost:32030/" } } }