前言
一般在應用程序開發到正式上線,在這個過程當中咱們會分爲多個階段,一般會有 開發、測試、以及正式環境等。每一個環境的參數配置咱們會使用不一樣的參數,所以呢,在ASP.NET Core中就提供了相關的環境API,方便咱們更好的去作這些事情。web
環境
ASP.NET Core使用ASPNETCORE_ENVIRONMENT來標識運行時環境。json
要取得系統變量ASPNETCORE_ENVIRONMENT,在3.0版本以前能夠經過注入IHostingEnvironment來獲取,3.x經過IWebHostEnvironment 請看以下代碼片斷:app
public class Startup { public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { } app.Run(async (context) => { await context.Response.WriteAsync( $"EnvironmentName: {env.EnvironmentName},IsDevelopment: {env.IsDevelopment()}" ); }); } }
網站啓動後IWebHostEnvironment會從ASPNETCORE_ENVIRONMENT中獲取內容,該變量能夠是咱們須要的任何值。也就是該變量不必定要必定是預設的值,咱們是能夠自定義的。async
好比咱們定義一個名爲Test環境測試
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { env.EnvironmentName = "test"; if (env.IsDevelopment()) { //TODO }else if (env.IsEnvironment("text")) { //TODO } app.Run(async (context) => { await context.Response.WriteAsync( $"EnvironmentName: {env.EnvironmentName},IsDevelopment: {env.IsDevelopment()}" ); }); }
注:在 Windows 和 macOS 上,環境變量和值不區分大小寫。 默認狀況下,Linux 環境變量和值要區分大小寫 。
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostContext, config) => { var env = hostContext.HostingEnvironment; config.SetBasePath(Path.Combine(env.ContentRootPath, "Configuration")) .AddJsonFile(path: "settings.json", optional: false, reloadOnChange: true) .AddJsonFile(path: $"settings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
經過上述代碼咱們,讀取咱們的配置文件回顯讀取setting.json並設置爲optional: false,表示該配置爲必要的配置;再往下繼續讀取再讀取settings.{env.EnvironmentName}.json文件。當加載遇到相同的Key那麼就會覆蓋掉前面的配置項。網站
環境設置
web.config配置環境變量ui
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <handlers> <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" /> </handlers> <aspNetCore processPath="dotnet" arguments=".\Demo.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout"> <environmentVariables> <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Test" /> </environmentVariables> </aspNetCore> </system.webServer> </configuration>
launch.json中配置ASPNETCORE_ENVIRONMENTcode
{ "version": "0.1.0", "configurations": [ { "name": ".NET Core Launch (web)", "type": "coreclr", "env": { "ASPNETCORE_ENVIRONMENT": "Development" } } ] }
Properties\launchSettings.jsonxml
"profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Test" } }, }