ASP.NET Core 應用程式發布命令:
dotnet publish [<PROJECT>] [-f|--framework] [-r|--runtime] [-o|--output] [-c|--configuration] [--version-suffix] [-v|--verbosity] [-h|--help]
發布樣本命令(產生在bin/release/netcoreapp1.1/publish
目錄下):
dotnet publish -c release
上面命令並沒有指定EnvironmentName
發布,什麼意思呢?比如 ASP.NET Core 應用程式中的appsettings.json
配置,測試環境和生產環境配置並不相同(比如資料庫連接字串),如果用上面的發布命令,我們還需要手動拷貝下不同環境的appsettings.json
檔案,以後要更改了,還需要再進行發布更新,很麻煩。
怎麼解決上面的問題,很簡單,指定下開發機或者伺服器的ASPNETCORE_ENVIRONMENT
環境變數,設定環境變數之後,執行dotnet *.dll
啟動程式的時候,ASP.NET Core 會自動載入此環境變數對應的appsettings.*.json
檔案,比如appsettings.Production.json
。
其實,我們使用 VS 2017 F5 調試項目的時候,也會預設設定ASPNETCORE_ENVIRONMENT
環境變數的,比如 ASP.NET Core 應用程式中的launchSettings.json
樣本配置:
"profiles": {"IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "launchUrl": "api/values", "environmentVariables": {"ASPNETCORE_ENVIRONMENT": "Development" }},"AspNetCore.Samples": { "commandName": "Project", "launchBrowser": true, "launchUrl": "api/values", "environmentVariables": {"ASPNETCORE_ENVIRONMENT": "Development" }, "applicationUrl": "http://localhost:59522"}}
Startup
樣本配置:
public Startup(IHostingEnvironment env){var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build();}
因為上面配置中,ASPNETCORE_ENVIRONMENT
設定的是Development
,我們在使用 VS 2017 F5 調試項目,會載入和使用項目下的appsettings.Development.json
設定檔,如果不存在此檔案,ASP.NET Core 預設會使用appsettings.json
設定檔。
那我們怎麼在伺服器上設定ASPNETCORE_ENVIRONMENT
環境變數呢?很簡單,敲個命令就可以了。
1. Windows 伺服器設定
命令列:
>setx ASPNETCORE_ENVIRONMENT "Development"SUCCESS: Specified value was saved.
或者(需要管理員權限)
>setx ASPNETCORE_ENVIRONMENT "Development" /MSUCCESS: Specified value was saved.
PowerShell
命令:
$Env:ASPNETCORE_ENVIRONMENT = "Prodction"
Windows 設定環境命令後,需要重新再開一個命令列dotnet *.dll
啟動項目,才會有效。
2. MacOS/Linux 伺服器設定
命令列:
export ASPNETCORE_ENVIRONMENT=development
dotnet *.dll
啟動項目的時候,我們可以看到當前的Hosting environment
,以便檢查是否正確,樣本:
> dotnet AspNetCore.Samples.dllHosting environment: ProdtctionContent root path: C:\Users\yuezh\Desktop\Demo\AspNetCore.SamplesNow listening on: http://*:5003Application started. Press Ctrl+C to shut down.
參考資料: