ASP.NET Core 指定环境发布(hosting environment)
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" /M
SUCCESS: 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.dll
Hosting environment: Prodtction
Content root path: C:\Users\yuezh\Desktop\Demo\AspNetCore.Samples
Now listening on: http://*:5003
Application started. Press Ctrl+C to shut down.
参考资料: