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
環境變數呢?很簡單,敲個指令就可以了。
命令列:
>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
啟動項目,才會有效。
命令列:
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.
參考資料:
dotnet-publish
Working with multiple environments
How to set the hosting environment in ASP.NET Core
以上是ASP.NET Core 應用程式發布命令實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!