二、运行环境配置
在进行项目开发时,常常要求开发环境,测试环境及正式环境的分离,并且不同环境运行的参数都是不一样的,比如监听地址,数据库连接信息等。当然我们把配置信息保存到一个文件中,每次发布的时候,可以先修改配置文件的内容,然后再进行程序发布,这样操作起来无疑是很麻烦,每次发布都得先确定对应的环境,然后修改配置信息,如果需要同时发布多个环境版本,那就得进行多次操作。
asp.net core 其实已经考虑到了这样的场景,我们可以先看下下面的代码:
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();
}
上面的代码是出现在startup.cs文件中,里面首先使用AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)加载appsettings配置文件,这个文件里可以放置所有环境共享的信息,后面有一句AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true),env.EnvironmentName其实就是系统环境,根据启动时设置的EnvironmentName不同,可以加载对应的配置文件内容。
现在的问题是如何去指定这个EnvironmentName?
1,通过命令行指定environment
在执行dotnet run之前,可以先执行以下下面的指令:
set ASPNETCORE_ENVIRONMENT= 环境名称,注意这里没有引号,直接把环境名称写成具体的值即可,比如 set ASPNETCORE_ENVIRONMNET=development
然后再执行dotnet run指令,这样当前运行就会按照set指令中设置的环境进行运行
2,直接给dotnet run指令传递具体参数
先看直接的执行效果:dotnet run --ASPNETCORE_ENVIRONMENT=development
具体做法:引入Microsoft.Extensions.Configuration.CommandLine,Microsoft.Extensions.Configuration.EnvironmentVariables库文件,然后在main方法中增加环境参数的支持,具体代码如下:
public class Program
{
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddEnvironmentVariables()
.AddCommandLine(args)
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("hosting.json")
.Build();
var host = new WebHostBuilder()
.UseEnvironment(config["ASPNETCORE_ENVIRONMENT"])
.UseConfiguration(config)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
}








