您的位置:首页 > 编程语言 > ASP

[转]ASP.NET Core 指定环境发布(hosting environment)

2017-12-19 16:05 666 查看
本文转自:https://www.cnblogs.com/xishuai/p/asp-net-core-set-hosting-environment-with-publish.html

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.


参考资料:

dotnet-publish

Working with multiple environments

How to set the hosting environment in ASP.NET Core
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: